具有可空外键的一对一关系

具有可空外键的一对一关系

本文介绍了具有可空外键的一对一关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在EF中创建一对一关系,其中外键可以为空(因此,可以将其称为0..1-to-0..1)

I want to create One-To-One relationship in EF where Foreign Keys can be null (So, It can be called 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中生成两列:

But it's generate two columns in table ProductInstance:

  • Sale_id-外键
  • SaleId
  • Sale_id - foreign key
  • 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这将是外键?

How can I do to get only one column SaleId which will be Foreign key?

推荐答案

EF不支持具有显式FK属性的one-to-one关联-没有HasForeignKey流利的API,并且如果您尝试使用ForeignKey数据解决该问题注释,则在迁移过程中会出现多重异常.

EF does not support one-to-one associations with explicit FK property - there is no HasForeignKey fluent API and if you try to workaround it with ForeignKey data annotation, you'll get multiplicity exception during the migration.

唯一的解决方案是删除ProductInstance.SaleId属性,最终得到模型:

The only solution is to remove the ProductInstance.SaleId property, ending up with model:

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"));

这篇关于具有可空外键的一对一关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 11:12