【发布时间】:2018-09-19 21:52:24
【问题描述】:
我正在使用 Code First,我正在尝试添加 2 条共享相同(构面)对象的记录。 EF 试图两次添加相同的共享对象,所以我得到了Violation of PRIMARY KEY constraint 错误。考虑一下..
XML
<RecipeSet xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Recipes>
<Recipe author="Mr. Cook" createdDate="08/30/2018" description="Cheesesteak with mushrooms" name="Mushroom Cheesesteak" recipe_id="13">
<Facet Taxonomy_id="1" name="Lunch" />
<Facet Taxonomy_id="1" name="Dinner" />
<Facet Taxonomy_id="2" name="American" />
</Recipe>
<Recipe author="Jane Doe" createdDate="10/01/2018" description="Vegan Hotdog" name="Vegan Hotdog" recipe_id="9">
<Facet Taxonomy_id="1" name="Snack" />
<Facet Taxonomy_id="1" name="Lunch" /> <!-- This is breaking EF! -->
<Facet Taxonomy_id="2" name="Vegetarian" />
</Recipe>
</Recipes>
</RecipeSet>
Recipe 和 Facets 具有多对多关系。
public class Recipe
{
[Key]
public int Recipe_id { get; set; }
public string Author { get; set; }
public DateTime CreatedDate { get; set; }
public string Description { get; set; }
public string Name { get; set; }
public virtual ICollection<Facet> Facets { get; set; }
}
//Facet needs to have a unique taxonomy id and name combination
public class Facet
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Facet_id { get; set; }
[Key]
[Column(Order = 0)]
public int Taxonomy_id { get; set; }
[Key]
[Column(Order = 1)]
[StringLength(500)]
public string Name { get; set; }
public virtual ICollection<Recipe> Recipes { get; set; }
}
public class RecipeContext : DbContext
{
public RecipeContext() : base("name=RecipeContextConn")
{
Database.SetInitializer<RecipeContext>(new CreateDatabaseIfNotExists<RecipeContext>());
}
public DbSet<Recipe> Recipe { get; set; }
public DbSet<Facet> Facet { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
}
}
// Automapper configuration
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<RecipeElement, Recipe>()
.ForMember(dest => dest.Facets, opt => opt.MapFrom(src => src.Facet));
cfg.CreateMap<FacetElement, Facet>();
});
Mapper = config.CreateMapper();
在 Foreach 循环后保存时,我的代码中断了。
foreach (var recipeElement in fullRecipeSet.Recipes.Recipe)
{
// Using Automapper to map from one object to another
Recipe recipeDto = Mapper.Map<Recipe>(recipeElement);
ctx.Recipe.Add(recipeDto);
}
ctx.SaveChanges();
我如何告诉 EF 只保存唯一的 Facet 一次?
【问题讨论】:
标签: c# entity-framework-6 many-to-many automapper