【发布时间】:2017-09-10 14:56:41
【问题描述】:
我正在使用 Entity Framework 6 开发一些 C# 项目
我想更新数据库,但在“运行种子方法”后出现此错误
Unable to determine the principal end of the 'CookerAPI.Models.Category_Recipe_Recipe' relationship. Multiple added entities may have the same primary key.
这是Seed方法的一部分:
context.Recipes.AddOrUpdate(x => x.Id_Recipe,
new Recipe() { Id_Recipe = 1, Id_User = 1, Id_Category_Main = 1, Name_Recipe = "zupa z kurek", Rate = 0, Level = "Łatwe", Date_Recipe = DateTime.Now, URL_Photo = "test", Time = 45, Number_Person = 4, Steps = 4, Instruction = "test" }
);
context.Categories_Recipes.AddOrUpdate(x => x.Id_Category_Recipe,
new Category_Recipe() { Id_Category_Recipe = 1, Id_Recipe = 1, Id_Category = 1 }
);
Category_Recipe 模型:
public class Category_Recipe
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id_Category_Recipe{ get; set; }
public int Id_Category { get; set; }
public int Id_Recipe { get; set;}
[ForeignKey("Id_Category")]
public Category Category { get; set; }
[ForeignKey("Id_Recipe")]
public Recipe Recipe { get; set; }
}
配方型号:
public class Recipe
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id_Recipe { get; set; }
public int Id_User { get; set; }
public int Id_Category_Main { get; set; }
public string Name_Recipe { get; set; }
public int Rate { get; set; } //rate 0-5
public string Level { get; set; }
public DateTime Date_Recipe { get; set; } //date of create
public string URL_Photo { get; set; } //URL of thumbnail
public int Time { get; set; } // in minutes
public int Number_Person { get; set; } // recipe for number of people
public int Steps { get; set; }
public string Instruction { get; set; }
[ForeignKey("Id_User")]
public User User { get;set;}
[ForeignKey("Id_Category_Main")]
public Category_Main Category_Main { get; set; }
public ICollection<Category_Recipe> Categories_Recipes { get; set; }
public ICollection<Comment> Comments { get; set; }
public ICollection<Element> Elements { get; set; }
public ICollection<Rate> Rates { get; set; }
}
问题出在哪里,我该如何解决?
【问题讨论】:
-
如果没有完整的重现,则不确定。但是,您可能会从模型中完全消除 Category_Recipe。并在 Recipe 上声明一个 ICollection
,在 Category 上声明一个 ICollection 。 EF 将在数据库中创建链接表,但您不必在模型中看到它。 -
好吧,我想创建多对多关系(Category - Recipe = Category_Recipe)。这是一个很好的解决方案。但是我对另一个多对多关系有同样的问题(配方-产品=元素,在这里我想在元素中再添加一行。那么如何解决呢?
-
如果没有完整的复制则不确定。
标签: c# asp.net entity-framework entity-framework-6