Entity Framework Code First - One-to-Many with a join/link table

*爱你&永不变心* 提交于 2019-12-03 20:23:17

You can use Entity splitting to achieve this

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

    public string Name { get; set; }

    public int BarId { get; set; }

    public virtual Bar Bar { get; set; }
}

Then in your custom DbContext class

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

The BarId column will be created as a not null column in FooBar table. You can check out Code First in the ADO.NET Entity Framework 4.1 for more details

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!