繁体   English   中英

首先使用实体​​框架代码与联结表一对多关系

[英]One to many relationship with junction table using Entity Framework code first

我首先使用EF6代码创建数据库,并努力使用联结表创建一对多关系。

这是我要执行的操作的一个示例:

Foo实体可以包含任意数量(0-n)的Bar实体,但是Bar实体不一定属于Foo 我可能希望其他类型的实体也包含一个或多个Bar ,因此Bar不包含其父级的外键很重要。

因此,联接表将如下所示:

Name        | FooBar
------------|-------
Primary Key | BarID
Key         | FooID

因此,如果我们按如下方式创建实体:

public class Foo
{
  public long ID { get; set; }
  public ICollection<Bar> Bars { get; set; }
}

public class Bar
{
  public long ID { get; set; }
}

然后配置它们:

public class FooConfiguration : EntityTypeConfiguration<Foo>
{
  HasKey(p => p.ID);
  HasMany(p => p.Bars)
    .WithRequired()
    .Map(m => {
      m.ToTable("FooBar");
      m.MapKey("FooKey");
    });
}

但这导致抛出以下异常:

An exception of type 'System.InvalidOperationException' occurred in mscorlib.dll but was not handled in user code. Additional information: The specified table 'FooBar' was not found in the model. Ensure that the table name has been correctly specified.

不幸的是,我不确定这意味着什么-我需要创建一个单独的FooBar实体吗?

如何配置这些实体,以便正确创建联接表?

谢谢!

很抱歉要重新启用此线程,但是我想共享一个我创建的用于处理WebApi的实用程序,该实用程序具有许多这种类型的关系实例。 我们有多个业务对象,每个业务对象都与EventHistory,Messages,Files等相关,并且混乱地跟踪所有FluentAPI函数。 这是我想出的:

    /// <summary>
    /// Maps a many-to-many relationship that can only be navigated from TSource to TTarget.
    /// </summary>
    /// <typeparam name="TSource">Source type that can navigate to TTarget.</typeparam>
    /// <typeparam name="TTarget">Target type that has no direct link back to TSource.</typeparam>
    /// <param name="modelBuilder">An instance of DbModelBuilder</param>
    /// <param name="expr">Lambda expression specifying the navigation property for this relationship from TSource to TTarget.</param>
    /// <param name="leftKey">Optional argument to override the foreign key to TSource</param>
    /// <param name="rightKey">Optional argument to override the foreign key to TTarget</param>
    public static void MapDirectionalManyToMany<TSource, TTarget>(DbModelBuilder modelBuilder, Expression<Func<TSource, ICollection<TTarget>>> expr, string tableName = null, string leftKey = null, string rightKey = null)
        where TSource : class
        where TTarget : class {

        modelBuilder.Entity<TSource>()
            .HasMany(expr)
            .WithMany()
            .Map(m => {
                m.MapLeftKey(leftKey ?? typeof(TSource).Name + "Id");
                m.MapRightKey(rightKey ?? typeof(TTarget).Name + "Id");
                m.ToTable(tableName ?? typeof(TSource).Name + typeof(TTarget).Name);
            });

    }

我这样应用这种关系:

ModelUtils.MapDirectionalManyToMany<MyResourceModel, SharedHistoryModel>(modelBuilder, x => x.History);
ModelUtils.MapDirectionalManyToMany<OtherResourceModel, SharedHistoryModel>(modelBuilder, x => x.History, "renamed_history");

如果您不想将foo的键存储在bar则必须进行多对多关系。 使它表现为一对多关系的方式取决于您的实现,仍然有一种方法可以确保bar只有一个foo ,但是对于EF6来创建联结表,唯一的方法是许多关系。

暂无
暂无

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

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