实体框架代码优先 - 一对许多与加入/链接表 [英] Entity Framework Code First - One-to-Many with a join/link table

查看:94
本文介绍了实体框架代码优先 - 一对许多与加入/链接表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能创建代码首先使用一个链接一多关系/它们之间的连接表?

Is it possible to create a One-to-Many relationship with Code First that uses a link/join table between them?

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



我想这个映射如下:

I want this to map as follows:

TABLE Foo
    FooId INT PRIMARY KEY
    ...

TABLE Bar
    BarId INT PRIMARY KEY

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

通过这一点,我将不得不确保富的能力,只有一个酒吧,但酒吧可以重新使用许多不同的FOOS。

With this, I would have the ability to make sure Foo only has one Bar, but that Bar could be re-used by many different Foos.

这可能与实体框架?我宁愿没有把钥匙Foo自己,因为我不想要一个空的外键。如果有可能,请提供使用流利的API,而不是数据注解的例子。

Is this possible with Entity Framework? I would prefer to not have to put the key in Foo itself because I don't want a nullable foreign key. If it is possible please provide an example using the Fluent API and not the data annotations.

推荐答案

您可以用实体分割来实现这种

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

然后在自定义的DbContext类

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



BarId 列将作为一个NOT NULL列在 FooBar的表中创建。您可以在ADO.NET实体框架4.1 以查看代码第一次更多详情

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

这篇关于实体框架代码优先 - 一对许多与加入/链接表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆