0
我有多對多關係的問題,因爲它會導致重複記錄。EF多對多導致重複
我有這些類:
class Flyer { Id, virtual ICollection<FlyerPage> Pages }
class FlyerPage { Id, FlyerId, virtual Flyer Flyer, ICollection<FlyerPageKeyword> Keywords }
而且
class FlyerPageKeyword { Id, Key, virtual ICollection<FlyerPage> Pages }
所以FlyerPage
和FlyerPageKeyword
是多對多。它的工作原理和記錄保存到數據庫。
但它也增加了關鍵字的重複。
我的背景:
public class Context : DbContext
{
public Context() : base("name=DbConnectionString")
{
Database.SetInitializer(new CreateDatabaseIfNotExists<Context>());
}
public virtual DbSet<Flyer> Flyers { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Configurations.Add(new FlyersEntityConfiguration());
modelBuilder.Configurations.Add(new FlyersPageEntityConfiguration());
modelBuilder.Configurations.Add(new FlyersPageKeywordsEntityConfiguration());
}
}
public class FlyersEntityConfiguration : EntityTypeConfiguration<Flyer>
{
public FlyersEntityConfiguration()
{
this.Map(flyer => flyer.ToTable("Flyer", "Flyers"));
this.HasMany(flyer => flyer.Pages)
.WithRequired(page => page.Flyer)
.HasForeignKey(page => page.FlyerId);
}
}
public class FlyersPageEntityConfiguration : EntityTypeConfiguration<FlyerPage>
{
public FlyersPageEntityConfiguration()
{
this.Map(pages => pages.ToTable("Page", "Flyers"));
this.HasMany(page => page.Keywords).WithMany(keywords => keywords.FlyerPages).Map(cfg =>
{
cfg.ToTable("PageKeywords", "Flyers.Page");
cfg.MapLeftKey("FlyerPageId");
cfg.MapRightKey("KeywordId");
});
}
}
public class FlyersPageKeywordsEntityConfiguration : EntityTypeConfiguration<FlyerPageKeyword>
{
public FlyersPageKeywordsEntityConfiguration()
{
this.ToTable("Keyword", "Flyers.Page");
}
}
而且Flyer
是聚合根,所以我就可以進行操作。無法只保存關鍵字。
var context = new Context();
var flyer = new Flyer
{
Pages = new List<FlyerPage>
{
new FlyerPage
{
Id = Guid.NewGuid(),
Keywords = new List<FlyerPageKeyword> {new FlyerPageKeyword {Key = "One"}}
},
new FlyerPage
{
Keywords = new List<FlyerPageKeyword> {new FlyerPageKeyword {Key = "Two"}}
}
}
};
context.Flyers.Add(flyer);
context.SaveChanges();
是'FlyerPage'和'FlyerPages'相同的(錯誤)? – grek40
是的,這是拼寫錯誤。 – Nerf
你能澄清這個問題嗎? 'FlyerPageId,KeywordId'的組合應該與您當前的設計是唯一的。 –