我希望在EF中创建一对一关系,其中外键可以为null(因此可以称为0..1至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
的外键?