我的情况下,我想存储一个地址,但它必须是可选的。
我的映射如下所示:
map.OwnsOne(x => x.Address, cb => cb.OwnsOne(l => l.Location));
但是当将我的DbContext的地址设置为空iam时出现此错误:
然后,我从构造函数实例化了Address和Location,现在可以保存实体。但是,当再次获取数据时,我也得到了一个实例化的地址,我真的想要一个空值。
不能创建可为空的拥有类型吗?
最佳答案
从EF Core 3开始,这已经成为可能。
Sample Code:
static void Main(string[] args)
{
using (var context = new OwnedEntityContext())
{
context.Add(new DetailedOrder
{
Status = OrderStatus.Pending,
OrderDetails = new OrderDetails
{
ShippingAddress = new StreetAddress
{
City = "London",
Street = "221 B Baker St"
}
//testing 3.0: "Yes, all dependents are now optional"
//reference: https://github.com/aspnet/EntityFrameworkCore/issues/9005#issuecomment-477741082
//NULL Owned Type Testing
//BillingAddress = new StreetAddress
//{
// City = "New York",
// Street = "11 Wall Street"
//}
}
});
context.SaveChanges();
}
//read test
using (var context = new OwnedEntityContext())
{
#region DetailedOrderQuery
var order = context.DetailedOrders.First(o => o.Status == OrderStatus.Pending);
Console.Write("NULL Owned Type Test, Is Billing Address NULL?");
//PRINTS FALSE
Console.WriteLine($"{order.OrderDetails.BillingAddress == null}");
#endregion
}
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
#region OwnsOneNested
modelBuilder.Entity<DetailedOrder>().OwnsOne(p => p.OrderDetails, od =>
{
od.OwnsOne(c => c.BillingAddress);
od.OwnsOne(c => c.ShippingAddress);
});
#endregion
#region OwnsOneTable
modelBuilder.Entity<DetailedOrder>().OwnsOne(p => p.OrderDetails, od =>
{
od.OwnsOne(c => c.BillingAddress);
od.OwnsOne(c => c.ShippingAddress);
od.ToTable("OrderDetails");
//Exception message:Microsoft.Data.SqlClient.SqlException:
//'Cascading foreign key 'FK_OrderDetails_DetailedOrders_OrderId' cannot
//be created where the referencing column 'OrderDetails.OrderId' is an identity column.
//Could not create constraint or index. See previous errors.'
//3.0 bug: https://github.com/aspnet/EntityFrameworkCore/issues/17448#issuecomment-525444101
//fixed in 3.1: https://github.com/aspnet/EntityFrameworkCore/pull/17458
od.Property("OrderId")
.ValueGeneratedNever();
});
#endregion
}