c# - Entity Framework 代码优先 - 具有连接/链接表的一对多

标签 c# entity-framework-4.1 ef-code-first fluent-interface

是否可以与使用链接/联接表的 Code First 创建一对多关系?

public class Foo {
    public int FooId { get; set; }
    // ...

    public int? BarId { get; set; }
    public virtual Bar Bar { get; set; }
}

public class Bar { 
    public int BarId { get; set; }
    // ...

    public virtual ICollection<Foo> Foos { get; set; }
}

我希望这映射如下:
TABLE Foo
    FooId INT PRIMARY KEY
    ...

TABLE Bar
    BarId INT PRIMARY KEY

TABLE FooBar
    FooId INT PRIMARY KEY / FOREIGN KEY
    BarId INT FOREIGN KEY

有了这个,我就能够确保 Foo 只有一个 Bar,但是这个 Bar 可以被许多不同的 Foo 重用。

Entity Framework 可以做到这一点吗?我宁愿不必将键放在 Foo 本身中,因为我不想要一个可为空的外键。如果可能,请提供使用 Fluent API 而不是数据注释的示例。

最佳答案

您可以使用实体拆分来实现此目的

public class Foo
{
    public int FooId { get; set; }

    public string Name { get; set; }

    public int BarId { get; set; }

    public virtual Bar Bar { get; set; }
}

然后在您的自定义 DbContext 类中
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Foo>().HasKey(f => f.FooId);
        modelBuilder.Entity<Foo>()
            .Map(m =>
                     {
                         m.Properties(b => new {b.Name});
                         m.ToTable("Foo");
                     })
            .Map(m =>
                     {
                         m.Properties(b => new {b.BarId});
                         m.ToTable("FooBar");
                     });

        modelBuilder.Entity<Foo>().HasRequired(f => f.Bar)
            .WithMany(b => b.Foos)
            .HasForeignKey(f => f.BarId);

        modelBuilder.Entity<Bar>().HasKey(b => b.BarId);
        modelBuilder.Entity<Bar>().ToTable("Bar");
    }
BarId列将在 FooBar 中创建为非空列 table 。您可以查看 Code First in the ADO.NET Entity Framework 4.1更多细节

关于c# - Entity Framework 代码优先 - 具有连接/链接表的一对多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7517675/

相关文章:

c# - 通过 parent child 的多个 Foreach 循环

c# - 使用 LINQ 排序

sql-server - EF4.1 : Possible to have zero-or-one to zero-or-one (0. .1 到 0..1) 关系?

c# - 无法确定类型 'X' 和 'X' 之间关联的主体端

c# - 多重性在关系 : EF code first one to one relationship with same primary key and foreign key 中的角色中无效

c# - EF6 代码首先添加迁移创建异常迁移但应用程序运行

c# - 如何将 GET 函数传递到 View/ViewModel?如何将数据绑定(bind)到 View (仅使用 C# 代码)?

c# - 将字符串列表存储在 ListView 的单独列中 (C#)

c# - Entity Framework Code First - 两个名称相同但 namespace 不同的实体

c# - 覆盖 SaveChanges 并设置 ModifiedDate,但如何设置 ModifiedBy?