本文介绍了实体框架6多对多想要插入重复的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 应该不是这么难!我即将放弃EF ... 我的模特有每周报纸版。每个版本都可以有很多分类。每个分类可以出现在一个或多个版本中。我的型号: public class 分类广告 { [Key,DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int ClassifiedId { get ; set ; } ... public virtual ICollection< EditionModel>版本{获取; set ; } } public class EditionModel { [Key,DatabaseGenerated(DatabaseGeneratedOption.None)] public int EditionId { get ; set ; } // 这是YYYYWW,WW =周数 public DateTime PublicationDate { get ; set ; } public virtual ICollection< Classifieds>分类{{span class =code-keyword>获取; set ; } } OnModelCreating覆盖: protected 覆盖 void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity< EditionModel>() .Property(z = > z .EditionId) .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None); modelBuilder.Entity< EditionModel>() .HasMany(c = > c.Classifieds)。 WithMany(d = > d.Editions) .Map(x = > { x.MapLeftKey( EditionId); x .MapRightKey( ClassifiedId); x.ToTable( EditionModelClassifieds); }); base .OnModelCreating(modelBuilder); } 创建分类广告操作代码(HTTP put): public async 任务< ActionResult>创建(分类分类, int [] EditionList) { var allPubs = PopulateEditionList(); // 当前和后续12个版本 classifieds.Editions = 新列表< EditionModel>(); foreach ( var p in EditionList) { var anEd = new EditionModel {EditionId = p} ; db.Set< EditionModel>()。Attach(anEd); classifieds.Editions.Add(anEd); } ... if (ModelState.IsValid) { var ads = db.Classifieds.Add(classifieds); await db.SaveChangesAsync()。ConfigureAwait( false ); return 查看( 收据,classifieds); } ... } 提交新的分类广告后,我得到违反PRIMARY KEY约束'PK_dbo.EditionModels'。无法在对象'dbo.EditionModels'中插入重复键。 为什么EF坚持要求插入重复行EditionModels而不是仅仅将连接表行链接到其中的现有行?即使我选择了EditionModels中尚不存在的版本,我也会收到此错误。我如何解决这个问题?解决方案 问题是EditionModel不是上下文的一部分。谢谢你,Slauma指出我正确的方向。更正的创建操作是: ... classifieds.Editions = new List(); foreach ( var p in EditionList) { var ed = await db.EditionModel.FindAsync( p); if (ed == null ) ed = new EditionModel {EditionId = p,PublicationDate =( from q in allPubs 其中 q.EditionId == p 选择 q)。单个()。PublicationDate}; InsertOrUpdate(ed); classifieds.Editions.Add(ed); } ... 其余代码如上所示。 It shouldn't be this hard! I am about to give up on EF...My model has weekly newspaper Editions. Each Edition can have many Classifieds. Each Classified can appear in one or more Editions. My models:public class Classifieds{ [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int ClassifiedId { get; set; } ... public virtual ICollection<EditionModel> Editions { get; set; }}public class EditionModel{ [Key, DatabaseGenerated(DatabaseGeneratedOption.None)] public int EditionId { get; set; } // This is YYYYWW, WW = week number public DateTime PublicationDate { get; set; } public virtual ICollection<Classifieds> Classifieds { get; set; }}The OnModelCreating override:protected override void OnModelCreating(DbModelBuilder modelBuilder){ modelBuilder.Entity<EditionModel>() .Property(z => z.EditionId) .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None); modelBuilder.Entity<EditionModel>() .HasMany(c => c.Classifieds) .WithMany(d => d.Editions) .Map(x => { x.MapLeftKey("EditionId"); x.MapRightKey("ClassifiedId"); x.ToTable("EditionModelClassifieds"); }); base.OnModelCreating(modelBuilder);}The Create Classifieds Action code (HTTP put):public async Task<ActionResult> Create(Classifieds classifieds, int[] EditionList){ var allPubs = PopulateEditionList(); // Current and next 12 editions classifieds.Editions = new List<EditionModel>(); foreach (var p in EditionList) { var anEd = new EditionModel { EditionId = p }; db.Set<EditionModel>().Attach(anEd); classifieds.Editions.Add(anEd); } ... if (ModelState.IsValid) { var ads = db.Classifieds.Add(classifieds); await db.SaveChangesAsync().ConfigureAwait(false); return View("Receipt", classifieds); } ...}On submit of a new Classifieds, I get "Violation of PRIMARY KEY constraint 'PK_dbo.EditionModels'. Cannot insert duplicate key in object 'dbo.EditionModels'."Why does EF insist on wanting insert duplicate rows in EditionModels instead of just linking the junction table row to an existing row therein? I get this error even if I select an Edition which does not yet exist in EditionModels. How do I get around this? 解决方案 The problem was that EditionModel was not part of the context. Thank you, Slauma for pointing me in the right direction. The corrected Create Action is:...classifieds.Editions = new List();foreach (var p in EditionList){ var ed = await db.EditionModel.FindAsync(p); if (ed == null) ed = new EditionModel { EditionId = p, PublicationDate = (from q in allPubs where q.EditionId == p select q).Single().PublicationDate }; InsertOrUpdate(ed); classifieds.Editions.Add(ed);}...The rest of the code is as above. 这篇关于实体框架6多对多想要插入重复的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-30 03:45