【发布时间】:2015-07-13 22:04:29
【问题描述】:
我有产品类:
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Language> Languages { get; set; }
}
语言类:
public class Language
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Product> Products { get; set; }
}
在我的 EntityTypeConfiguration 中:
public class ProductMap : EntityTypeConfiguration<Product>
{
public ProductMap()
{
HasKey(m => m.Id);
Property(p => p.Name).IsRequired();
HasMany(p => p.Languages)
.WithMany(l => l.Products)
.Map(x => x.ToTable("ProducLanguages")
.MapLeftKey("ProductId")
.MapRightKey("LanguageId"));
//Table
ToTable("Products");
}
}
这会按预期创建第三个表,但是当我使用以下种子执行更新数据库时:
protected override void Seed(EcoomerceContext context)
{
var languages = new List<Language>
{
new Language {Name = "Portuguese"},
new Language {Name = "English"},
new Language {Name = "Spanish"}
};
var languagePt = new List<Language>
{
new Language {Name = "Portuguese"},
};
//languages.ForEach(a => context.Languages.Add(a));
new List<Product>
{
new Product {Name = "NameProduct1", Languages = languages},
new Product {Name = NameProduct2 , Languages = languagePt},
}.ForEach(a => context.Products.Add(a));
context.SaveChanges();
}
它像这样更新关系表 ProducLanguages:
它正在插入一种不存在的语言(数字 4),我期望的结果是:
我做错了什么?
提前致谢。
【问题讨论】:
标签: c# .net entity-framework ef-code-first migration