【发布时间】:2016-11-19 19:52:53
【问题描述】:
我想在 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 中生成两列:
-
Sale_id- 外键 SaleId
这里是生成的迁移代码:
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,这将是外键?
【问题讨论】:
-
为什么要同时创建一个与 Sale 实例的关联和一个包含 Sale 实例 ID 的属性?这就是在您的表中创建 2 列的原因。
-
EF 代表实体框架,因此它仅适用于数据作为实体而不是值对象。也许在后面的版本中它也支持值对象。
标签: c# entity-framework one-to-one