我想在 EF 中创建一对一关系,其中外键可以为空(因此,可以将其称为 0..1-to-0..1)
public class ProductInstance
{
public int Id { get; set; }
public int SaleId { get; set; }
public Sale Sale { get; set; }
}
public class Sale
{
public int Id { get; set; }
public ProductInstance ProductInstance { get; set; }
}
FluentAPI
配置:
modelBuilder.Entity<Sale>()
.HasOptional(x => x.ProductInstance)
.WithOptionalPrincipal(x => x.Sale);
但它在表中生成两列ProductInstance
:
这是生成的迁移代码:
CreateTable(
"dbo.ProductInstances",
c => new
{
Id = c.Int(nullable: false, identity: true),
SaleId = c.Int(nullable: false),
Sale_Id = c.Int(),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.Sales", t => t.Sale_Id)
.Index(t => t.Sale_Id);
我怎样才能只得到一列SaleId
哪个将是外键?
EF 不支持one-to-one
与显式 FK 属性的关联 - 没有HasForeignKey
流畅的 API,如果你尝试解决它ForeignKey
数据注释,您将在迁移过程中遇到多重异常。
唯一的解决办法就是删除ProductInstance.SaleId
属性,最终模型:
public class ProductInstance
{
public int Id { get; set; }
public Sale Sale { get; set; }
}
public class Sale
{
public int Id { get; set; }
public ProductInstance ProductInstance { get; set; }
}
和配置:
modelBuilder.Entity<Sale>()
.HasOptional(x => x.ProductInstance)
.WithOptionalPrincipal(x => x.Sale)
.Map(a => a.MapKey("SaleId"));
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)