实体框架6代码优先 - 通过注释多对多的方式

Ant*_*ton 12 .net c# entity-framework ef-code-first

是否有可能在实体框架6中创建具有代码优先和注释的单向多对多关联?例:

class Currency
{
    public int id { get; set; }
}

class Country
{
    public int id { get; set; }

    // How i can annotate this property to say EF that it is many-to-many
    // and it should create mapping table?
    // I don't need navigation property to Country in Currency class!
    public virtual IList<Currency> currencies { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

在Java + JPA注释中,我可以通过这种方式实现我需要的东西:

@OneToMany
@JoinTable(name = "MAPPING_TABLE", joinColumns = {
    @JoinColumn(name = "THIS_ID", referencedColumnName = "ID")
}, inverseJoinColumns = {
    @JoinColumn(name = "OTHER_ID", referencedColumnName = "ID")
})
Run Code Online (Sandbox Code Playgroud)

那么,EF有相同的功能吗?

Myk*_*lis 30

您可以通过使用Fluent API显式指定关系来完成此操作.覆盖类的OnModelCreating()方法DbContext,并在覆盖中指定映射表的详细信息,如下所示:

class MyContext : DbContext
{
    public DbSet<Currency> Currencies { get; set; }
    public DbSet<Country> Countries { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Country>()
            .HasMany(c => c.Currencies)
            .WithMany()                 // Note the empty WithMany()
            .Map(x =>
            {
                x.MapLeftKey("CountryId");
                x.MapRightKey("CurrencyId");
                x.ToTable("CountryCurrencyMapping");
            });

        base.OnModelCreating(modelBuilder);
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意 - 在我的快速测试中 - Include()在加载EF对象时,您必须使用Currencies属性才能填充列表:

            var us = db.Countries
                        .Where(x => x.Name == "United States")
                        .Include(x=>x.Currencies)
                        .First();
Run Code Online (Sandbox Code Playgroud)

编辑

如果您真的想要使用数据注释完成所有操作,而根本不使用Fluent,那么您可以在其他地方明确指出连接表的模型.但是,这种方法存在各种可用性缺点,因此Fluent方法似乎是最好的方法.

class Country
{
    public int Id { get; set; }
    public virtual ICollection<CountryCurrency> CountryCurrencies { get; set; }
}

class Currency
{
    public int Id { get; set; }
}

class CountryCurrency
{
    [Key, Column(Order=0)]
    public virtual int CountryId { get; set; }
    [Key, Column(Order=1)]
    public virtual int CurrencyId { get; set; }

    public virtual Country Country { get; set; }
    public virtual Currency Currency { get; set; }
}
Run Code Online (Sandbox Code Playgroud)


bay*_*ncu 0

我认为您想学习如何将关系与 EF 代码优先实体分开。我在这里开始了一个关于这个问题的话题。我想将关系对象与实体分开,并且我使用了部分类。在我的问题中,我想学习如何按班级分类分隔部分班级。但不能。

当我使用 NHibernate 时,我在这里使用 XML 映射和创建关系,在 java 平台中也是同样的事情。但我认为实体框架还没有准备好。