EF 6.多个添加的实体可以具有相同的主键。错误

时间:2017-09-10 14:56:41

标签: c# asp.net entity-framework entity-framework-6

我正在使用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.

以下是种子方法的一部分:

            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; }

    }

问题出在哪里?我该如何解决?

1 个答案:

答案 0 :(得分:0)

解决方案:

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.Add(new Category_Recipe() { Id_Recipe = 3, Id_Category = 3 });
    context.SaveChanges();