簡體   English   中英

實體框架6代碼優先 - 通過注釋多對多的方式

[英]Entity framework 6 code first - one way many to many via annotations

是否有可能在實體框架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; }
}

在Java + JPA注釋中,我可以通過這種方式實現我需要的東西:

@OneToMany
@JoinTable(name = "MAPPING_TABLE", joinColumns = {
    @JoinColumn(name = "THIS_ID", referencedColumnName = "ID")
}, inverseJoinColumns = {
    @JoinColumn(name = "OTHER_ID", referencedColumnName = "ID")
})

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

您可以通過使用Fluent API顯式指定關系來完成此操作。 覆蓋DbContext類的OnModelCreating()方法,並在覆蓋中指定映射表的詳細信息,如下所示:

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

請注意 - 在我的快速測試中 - 在加載EF對象時,必須Include() Currencies屬性以填充列表:

            var us = db.Countries
                        .Where(x => x.Name == "United States")
                        .Include(x=>x.Currencies)
                        .First();

編輯

如果您真的想要使用數據注釋完成所有操作,而根本不使用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; }
}

我想你想學習如何將關系與EF代碼第一實體分開。 我在這里開始討論這個問題。 我想將關系對象與實體分開,我使用了部分類。 在我的問題中,我想學習如何按班級分類。 但不可能。

雖然我在使用NHibernate,但我在這里使用XML映射和創建關系,在java平台上是一回事。 但我認為實體框架還沒有准備好。

您可以在EF 6中輕松地在代碼中執行此操作。

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

   public virtual ICollection<Currency> Currencys {get;set;}//don't worry about the name,     pluralisation etc


}

public class Currency
{

   public int ID {get;set;}

   public virtual ICollection<Country> Countrys {get;set;}//same as above - 

}

編譯它,運行它,嘿presto - 魔術連接表在后台。 取決於命名慣例是否打擾你。 我個人認為如果你先做代碼,你應該在代碼中完成所有操作。 有些人更喜歡注釋,有些人更喜歡流暢的API - 使用您喜歡的任何一種。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM