主键上的实体代码首次播种问题

时间:2018-10-16 16:32:36

标签: database entity-framework-6 code-first seeding

我所有的表都有自动生成的ID。

[Required, Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
[MaxLength(50)]
public string Id { get; set; }
/// <summary>
/// This is only for sorting transactions by number.
/// </summary>
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public long Nth { get; set; }

这很好,除了在种子中创建数据时。 我们生成一个id数组,只是进行插入或更新,但我们总是得到 主键违反Violation of PRIMARY KEY constraint 'PK_dbo.ActivityLogs'. Cannot insert duplicate key in object 'dbo.ActivityLogs'. The duplicate key value is (05zwZ4VMKA0jr8NQz1EZ8qEB7GX23x).

奇怪的是,它可以在某些表上工作,而在其他表上却不行。 有人知道为什么吗?这是错误吗?

var _50activitylogIdsForTask = new [] {"18oB57zqrvzwrW9knGVl8ywRVbpdNL", "7nGPVlLx8AJWBr2KPxVlLMz0RKQXJk", "rlAezJPwj9O3LDdKorXbW9504q16EL", "wbJNzyxBVjygDRmJByd0WOQpYXEnZk", "VKlGJLAYqnBNa0mo18bP0nPxeX3Da4", "D67mBA5yzP1y0pwGO25dpPrb4E3n1G", "oZXO1b2lYNlA9wW1n5blw4qLEV9jGw", "m6gQRYz4VNwwXY0WEdZbYNw1XbeL7l", "gkWjenlPmMVLgBrxmlnYBRyZ9aApbo" //etc };
IList<ActivityLog> activityLogsForTask = new List<ActivityLog>();
for (int ii = 0; ii < 50; ii++)
{
    activityLogsForTask.Add(new ActivityLog()
    {
        Id = _50activitylogIdsForTask[ii],                    
        Sections = Sections.TaskTemplateMgmt,
        Action = Operations.Created,
        Details = "A new task, " + _50taskNames[ii] + " has been created, successfully.",
        CreatedDate = new DateTime(2018,9,15,13,1,57),
        CreatedById = adminid,
    });
}
context.ActivityLogs.AddOrUpdate(xx => xx.Nth, activityLogsForTask.ToArray());

我们一直在解决的方法是删除数据库并再次运行。 或先于context.ActivityLogs.RemoveRange(curActivities); context.SaveChanges();

首先AddOrUpdate

任何帮助将不胜感激。 谢谢。

0 个答案:

没有答案