I have Product class:
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Language> Languages { get; set; }
}
Language class:
public class Language
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Product> Products { get; set; }
}
In my 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");
}
}
This creates a third table as expected, but when I executed my update-database with the following seed:
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();
}
It updates the relationship table ProducLanguages like this:
It is inserting a language that does not exist (number 4), the result I expect is:
What Am I doing wrong ?
Thanks in advance.