entity framework6代码优先 – 通过注释多对多的方式

是否有可能在entity framework6中创建具有代码优先和注释的单向多对多关联? 例:

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 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有相同的function吗?

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

 class MyContext : DbContext { public DbSet Currencies { get; set; } public DbSet Countries { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity() .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 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代码第一实体分开。 我在这里开始讨论这个问题。 我想将关系对象与实体分开,我使用了部分类。 在我的问题中,我想学习如何按class级分类。 但不可能。

虽然我在使用NHibernate,但我在这里使用XML映射和创建关系,在java平台上是一回事。 但我认为entity framework还没有准备好。

您可以在EF 6中轻松地在代码中执行此操作。

  public class Country { public int ID {get;set;} public virtual ICollection Currencys {get;set;}//don't worry about the name, pluralisation etc } public class Currency { public int ID {get;set;} public virtual ICollection Countrys {get;set;}//same as above - } 

编译它,运行它,嘿presto – 魔术连接表在后台。 取决于命名惯例是否打扰你。 我个人认为如果你先做代码,你应该在代码中完成所有操作。 有些人更喜欢注释,有些人更喜欢流畅的API – 使用您喜欢的任何一种。