多线程EF6中的主键冲突

Joh*_*dom 2 c# multithreading entity-framework primary-key ef-code-first

我正在开发一个C#控制台应用程序,它从Guild Wars 2 API下载数据并使用Entity Framework 6将其输入到我的数据库中.我正在尝试使用多线程,以便我可以加快输入大量的数据进入我的数据库.

问题是当代码DBContext.SaveChanges()在我的AddRecipes方法中运行到我的调用时,返回以下错误:

违反PRIMARY KEY约束'PK_dbo.Items'.无法在对象'dbo.Items'中插入重复键.重复键值为(0).

以下是与我的问题相关的代码部分:

class Program
{
    private static ManualResetEvent resetEvent;
    private static int nIncompleteThreads = 0;

    //Call this function to add to the dbo.Items table
    private static void AddItems(object response)
    {
        string strResponse = (string)response;

        using (GWDBContext ctx = new GWDBContext())
        {
            IEnumerable<Items> itemResponse = JsonConvert.DeserializeObject<IEnumerable<Items>>(strResponse);

            ctx.Items.AddRange(itemResponse);
            ctx.SaveChanges();
        }

        if (Interlocked.Decrement(ref nIncompleteThreads) == 0)
        {
            resetEvent.Set();
        }
    }

    //Call this function to add to the dbo.Recipes table
    private static void AddRecipes(object response)
    {
        string strResponse = (string)response;

        using (GWDBContext ctx = new GWDBContext())
        {
            IEnumerable<Recipes> recipeResponse = JsonConvert.DeserializeObject<IEnumerable<Recipes>>(strResponse);

            ctx.Recipes.AddRange(recipeResponse);

            foreach(Recipes recipe in recipeResponse)
            {
                ctx.Ingredients.AddRange(recipe.ingredients);
            }
            ctx.SaveChanges(); //This is where the error is thrown
        }

        if (Interlocked.Decrement(ref nIncompleteThreads) == 0)
        {
            resetEvent.Set();
        }
    }

    static void GetResponse(string strLink, string type)
    {
        //This method calls the GW2 API through HTTPWebRequest
        //and store the responses in a List<string> responseList variable.
        GWHelper.GetAllResponses(strLink);

        resetEvent = new ManualResetEvent(false);
        nIncompleteThreads = GWHelper.responseList.Count();

        //ThreadPool.QueueUserWorkItem creates threads for multi-threading
        switch (type)
        {
            case "I":
                {
                    foreach (string strResponse in GWHelper.responseList)
                    {
                        ThreadPool.QueueUserWorkItem(new WaitCallback(AddItems), strResponse);
                    }
                    break;
                }
            case "R":
                {
                    foreach (string strResponse in GWHelper.responseList)
                    {
                        ThreadPool.QueueUserWorkItem(new WaitCallback(AddRecipes), strResponse);
                    }
                    break;
                }
        }

        //Waiting then resetting event and clearing the responseList
        resetEvent.WaitOne();           
        GWHelper.responseList.Clear();
        resetEvent.Dispose();
    }

    static void Main(string[] args)
    {
        string strItemsLink = "items";
        string strRecipesLink = "recipes";

        GetResponse(strItemsLink, "I");
        GetResponse(strRecipesLink, "R");

        Console.WriteLine("Press any key to continue...");
        Console.ReadLine();
    }
Run Code Online (Sandbox Code Playgroud)

这是我的DBContext类:

public class GWDBContext : DbContext
{
    public GWDBContext() : base("name=XenoGWDBConnectionString") { }

    public DbSet<Items> Items { get; set; }
    public DbSet<Recipes> Recipes { get; set; }
    public DbSet<Ingredient> Ingredients { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
    }
}
Run Code Online (Sandbox Code Playgroud)

这里也是我的表类(我知道名字很混乱,我正在重写它们):

public class Items
{
    public Items()
    {
        Recipes = new HashSet<Recipes>();
        Ingredients = new HashSet<Ingredient>();
    }

    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.None)] //This attribute makes sure that the id column is not an identity column since the api is sending that).
    public int id { get; set; }

    .../...
    public virtual ICollection<Recipes> Recipes { get; set; }
    public virtual ICollection<Ingredient> Ingredients { get; set; }
}

public class Recipes
{
    public Recipes()
    {
        disciplines = new List<string>();
        ingredients = new HashSet<Ingredient>();
    }

    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.None)] //This attribute makes sure that the id column is not an identity column since the api is sending that).
    public int id { get; set; }
    public string type { get; set; }

    [ForeignKey("Items")] //This attribute points the output_item_id column to the Items table.

    .../...
    private List<string> _disciplines { get; set; }
    public List<string> disciplines
    {
        get { return _disciplines; }
        set { _disciplines = value; }
    }

    [Required]
    public string DisciplineAsString
    {
        //get; set;
        get { return string.Join(",", _disciplines); }
        set { _disciplines = value.Split(',').ToList(); }
    }

    public string chat_link { get; set; }

    public virtual ICollection<Ingredient> ingredients { get; set; }
    public virtual Items Items { get; set; }
}

public class Ingredient
{
    public Ingredient()
    {
        Recipe = new HashSet<Recipes>();
    }

    [Key]
    public int ingredientID { get; set; }

    [ForeignKey("Items")] //This attribute points the item_id column to the Items table.
    public int item_id { get; set; }
    public int count { get; set; }

    public virtual ICollection<Recipes> Recipe { get; set; }
    public virtual Items Items { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

以下链接解释了Items/Recipes类的返回内容:

项目

食谱

我注意到在删除外键约束和public virtual Items Items { get; set; }代码后,数据将被正确保存.我相信我的错误与public virtual Items ItemsRecipes课程有关.但根据我的理解,我需要在类中拥有该虚拟变量,以便Entity Framework可以知道类之间的关系.那么为什么在我的类中使用该虚拟变量会导致抛出主键违规?

Yve*_*omb 6

您只需要食谱中的项目列表.如果您需要搜索哪些食谱具有特定项目,您可以通过搜索食谱的外键(项目的主键)来执行此操作.

代码存在一个基本的命名缺陷.你有一个食谱类,然后是一个名为食谱的食谱列表.与物品相同.

然后你有一个[ForeignKey("Items")]Recipes 的外键 .这是哪个项目?列表或对象项.它很容易出错.

将您的课程重命名为RecipeItem

public class Recipe
{ 
    public Recipe()


public class Item
{
    public Item()
Run Code Online (Sandbox Code Playgroud)

此外-具有重复Id0,因为在评论中提到的,它听起来就像是Id没有被设置.

查看食谱的链接:

{
    .../...
    "ingredients": [
            { "item_id": 19684, "count": 50 },
            { "item_id": 19721, "count": 1 },
            { "item_id": 46747, "count": 10 }
    ],
    "id": 7319,
    .../...
}
Run Code Online (Sandbox Code Playgroud)

食谱不应包含项目列表,而应包含成分列表.类结构应该是:

Recipe has:
public virtual ICollection<Ingredient> Ingredients { get; set; }

Ingredient has:
public virtual ICollection<Item> Items { get; set; }
Run Code Online (Sandbox Code Playgroud)

Item类没有成分或配方列表,这些列表是通过与外键匹配该项目的主键,或在配方外键数据库配料匹配的主键查询的成分数据库检索项目成分 - 然后你可以加入以找到这些成分的任何项目.

因此,请进行以下更改:

在Item类中不需要提及Recipe或Ingredients.

public Item() // remove pluralisation
{
    // Remove these from the constructor,
    // Recipes = new HashSet<Recipes>();
    // Ingredients = new HashSet<Ingredient>();
}

// remove these from the class.
// public virtual ICollection<Recipes> Recipes { get; set; }
// public virtual ICollection<Ingredient> Ingredients { get; set; }
Run Code Online (Sandbox Code Playgroud)

成分有许多项目 - ergo项目的集合

public Ingredient()
{
    // You don't need a collection of Recipes - 
    // you need a collection of Items.
    // Recipe = new HashSet<Recipes>();
}
.../...
[ForeignKey("Item")] // change this
public Item Item // include an Item object - the PK of the
    // Item is the FK of the Ingredient


.../...
// Remove Recipes
// public virtual ICollection<Recipes> Recipe { get; set; }
public virtual ICollection<Item> Items { get; set; }
Run Code Online (Sandbox Code Playgroud)

我更喜欢使用变量Item Item的对象名称.

食谱有许多成分 - ergo一系列成分

public Recipes()
{
    disciplines = new List<string>();
    ingredients = new HashSet<Ingredient>();
}
.../...
// [ForeignKey("Items")] remove this
[ForeignKey("Ingredient")] 
public Ingredient Ingredient // include as Ingredient object 
    // the PK of the Ingredient is the FK for the Recipe

.../...
public virtual ICollection<Ingredient> Ingredients { get; set; }
// The Recipe does not have an Item, the Ingredient has 
// has a collection of <Item> Items
// public virtual Items Items { get; set; }
Run Code Online (Sandbox Code Playgroud)

另外我不确定你为什么使用Hashsets.如果你没有特别的理由使用它们,我会把它们变成列表.

如果这不能修复您的代码,我会检查其余部分.