Csharp/C#教程:多对多映射不起作用 – EF 4.1 RC分享


多对多映射不起作用 – EF 4.1 RC

更新:经过一番研究后,我的多对多映射似乎无法正常工作。 嗯…

我正在将数据访问项目从EF 4.1 CTP4升级到EF 4.1 RC,我遇到了新的EntityTypeConfiguration设置问题。

具体来说,我遇到了多对多关系的问题。 当我试图获取.First()项时,我得到一个Sequence contains no elementsexception。

特别的例外并不是那么有趣。 所有它说的是没有项目我知道集合中应该有项目 – 所以我的新映射必定存在问题。

这是我到目前为止的代码:

产品型号

 public class Product : DbTable { //Blah public virtual ICollection Categories { get; set; } public Product() { //Blah Categories = new List(); } } 

BaseConfiguration

 public class BaseConfiguration : EntityTypeConfiguration where T : DbTable { public BaseConfiguration() { this.HasKey(x => x.Id); this.Property(x => x.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity); this.Property(x => x.UpdatedOn); this.Property(x => x.CreatedOn); } } 

ProductConfiguration

 public class ProductConfiguration : BaseConfiguration { public ProductConfiguration() { this.ToTable("Product"); //Blah this.HasMany(x => x.Categories) .WithMany() .Map(m => { m.MapLeftKey("Tag_Id"); m.MapRightKey("Product_Id"); m.ToTable("ProductCategory"); }); } } 

以前的CTP4映射工作!

 this.HasMany(x => x.Categories) .WithMany() .Map("ProductCategory", (p, c) => new { Product_Id = p.Id, Tag_Id = c.Id }); 

谁能看到任何需要修理的东西? 如果您希望我提供更多代码,请与我们联系。

编辑:更多代码

DBTABLE

 public class DbTable : IDbTable { public int Id { get; set; } public DateTime UpdatedOn { get; set; } public DateTime CreatedOn { get; set; } } 

标签

 public class Tag { public int Id { get; set; } public string Name { get; set; } public string Slug { get; set; } public bool Visible { get; set; } public virtual TagType TagType { get; set; } } 

TagConfiguration

 public class TagConfiguration : EntityTypeConfiguration { public TagConfiguration() { this.ToTable("Tags"); this.HasKey(x => x.Id); this.Property(x => x.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity).HasColumnName("tag_id"); this.Property(x => x.Name).HasMaxLength(300).HasColumnName("tag_name"); this.Property(x => x.Slug).HasMaxLength(500).HasColumnName("tag_slug"); this.Property(x => x.Visible).HasColumnName("tag_visible"); this.HasRequired(x => x.TagType).WithMany(tt => tt.Tags).Map(m => m.MapKey("tagtype_id")); } } 

是的,这是一个遗留数据库,其命名约定高达boohai 。

我知道Tag类必须正确连接,因为Product有另一个属性Specialization ,它也映射到Tag并正确加载。 但要注意它是以一对多的方式映射的。 所以它似乎是Tag的多对多。

我将开始检查是否有任何多对多关联正在运行。

您需要指定两个导航属性以执行多对多映射。

尝试在指向产品的WithMany属性中添加lambda:

 this.HasMany(x => x.Categories) .WithMany(category=>category.Products) .Map(m => { m.MapLeftKey(t => t.TagId, "Tag_Id"); m.MapRightKey(t => t.ProductId, "Product_Id"); m.ToTable("ProductCategory"); }); 

(交叉手指……)

我还没有使用Code-First方法,但在使用POCO时我必须启用Lazy-Loading,才能使导航属性工作。 这当然是设计的,但我不知道你是否必须为Code-First明确启用此行为。

上述就是C#学习教程:多对多映射不起作用 – EF 4.1 RC分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/1011059.html

(0)
上一篇 2021年12月29日
下一篇 2021年12月29日

精彩推荐