多线程EF6中的主键冲突

时间:2017-07-22 23:30:23

标签: c# multithreading entity-framework ef-code-first primary-key

我正在开发一个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();
    }

这是我的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>();
    }
}

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

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

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

Items

Recipes

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

1 个答案:

答案 0 :(得分:6)

您只需要食谱中的项目列表。如果您需要搜索哪些食谱具有特定项目,您可以通过搜索食谱的外键(项目的主键)来实现。

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

然后您有食谱的外键[ForeignKey("Items")]。这是哪个项目?列表或对象项。它很容易出错。

将您的课程重命名为RecipeItem

public class Recipe
{ 
    public Recipe()


public class Item
{
    public Item()

另外 - 如评论中所述,Id的{​​{1}}重复,听起来似乎没有设置0

查看食谱的链接:

Id

食谱不应包含物品清单,而应包含成分清单。类结构应该是:

{
    .../...
    "ingredients": [
            { "item_id": 19684, "count": 50 },
            { "item_id": 19721, "count": 1 },
            { "item_id": 46747, "count": 10 }
    ],
    "id": 7319,
    .../...
}

Recipe has: public virtual ICollection<Ingredient> Ingredients { get; set; } Ingredient has: public virtual ICollection<Item> Items { get; set; } 类没有成分或配方列表,这些列表是通过查询成分上的数据库项目来检索的,外键与项目的主键匹配,或数据库成分上食谱外键与成分的主键相匹配 - 然后您可以进行连接以查找这些成分的任何项目。

因此,请进行以下更改:

不需要在Item类中提及食谱或配料。

Item

成分有很多项目 - 项目集合

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

我更喜欢using the object name for the variable Item Item

食谱中含有许多成分 - 这是成分的集合

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

此外,我不确定您使用Hashsets的原因。如果你没有特别的理由使用它们,我会把它们变成列表。

如果这不能修复您的代码,我会审核其余部分。