繁体   English   中英

实体框架代码优先 - 具有连接/链接表的一对多

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

是否可以与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重用。

实体框架可以实现吗? 我宁愿不必将密钥放在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表中创建为非空列。 您可以在ADO.NET Entity Framework 4.1中查看Code First以获取更多详细信息

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM