【问题标题】:EF Fluent API map 0..1 to 0..1 relationshipEF Fluent API 映射 0..1 到 0..1 的关系
【发布时间】:2012-09-08 00:59:39
【问题描述】:

大家好,我有一个关于 EF Fluent API(代码优先:P)的问题。在我的模型中,我有

public class TABLE_A
{
   public virtual long Id {get; set;}
   .... 
   public virtual TABLE_B MyTableBRef {get; set;}
}


public class TABLE_B
{
   public virtual long Id {get; set;}
   .... 
   public virtual TABLE_A MyTableARef {get; set;}
}

我应该如何映射 0..1 到 0..1 的关系?

在 TABLE_B 的数据库中,我有一列 (FK) 引用了 TABLE_A 的 PK。

【问题讨论】:

    标签: entity-framework code-first fluent


    【解决方案1】:

    如果您使用的列不是TABLE_B 的PK,则不能在两边都有导航属性。

    public class TABLE_A
    {
       public virtual long Id {get; set;}
    }
    
    
    public class TABLE_B
    {
       public virtual long Id {get; set;}
       .... 
       public virutal TABLE_A MyTableARef {get; set;}
    }
    
    public class MyContext : DbContext
    {
        public DbSet<TABLE_A> As { get; set; }
        public DbSet<TABLE_B> Bs { get; set; }
    
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<TABLE_B>()
               .HasRequired(b => b.MyTableARef)
               .WithMany()
               .Map(b => b.MapKey("FK_Column_name));
        }
    }
    

    如果 TABLE_B 的 PK 也是 TABLE_A 的 FK,那么您可以使用共享的 PK 映射和两侧的导航属性。

    编辑:

    您可以使用共享PK映射如下

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<TABLE_B>()
           .HasRequired(b => b.MyTableARef)
           .WithOptional(a => a.MyTableBRef);
    }
    

    TABLE_BId 也是 TABLE_A 的 FK。

    【讨论】:

    • 我明白 .. 但如果您使用 DBFirst emdx,我可以将接口配置为 0 .. 1 到 0 .. 1 并且实体在两者上都有导航属性。数据库在 FK TABLE_A 列中(使用 DBFirst 表是相等的)我如何使用 PK 与双方的导航映射属性共享。
    • “HasRequired”和“WithMany”如何适合关系 0..1 到 0..1 的问题?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多