【问题标题】:Entity Framework Code First - One-to-Many with a join/link table实体框架代码优先 - 一对多与连接/链接表
【发布时间】:2011-09-22 15:49:27
【问题描述】:

是否可以使用 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 而不是数据注释的示例。

【问题讨论】:

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


    【解决方案1】:

    您可以使用实体拆分来实现这一点

    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 表中创建为非空列。您可以查看Code First in the ADO.NET Entity Framework 4.1了解更多详情

    【讨论】:

    • 好的,它创建了一个看起来正确的 FooBar 表。吧台看起来不错。唯一的问题是它将Foo表创建为Foo1而不是Foo?它还使 FooBar 上的 BarId 可以为空,我想避免这种情况,这就是我想要链接表的原因。
    • 仍然不是 100% 正确。它完全按照我想要的方式映射架构,但实体无法正常工作。它迫使我的 Foo 总是有一个 Bar,但事实并非如此。我尝试将 Foo.BarId 切换为 int?但随后它尝试在连接表中插入空值。当 Bar 不存在时,我根本不想要连接表中的一行,而不是空键。
    • @Dismissile 是的,它将始终插入FooBar。 AFAIK 您的场景无法精确建模。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-09
    • 1970-01-01
    • 1970-01-01
    • 2012-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多