![](/img/trans.png)
[英]SqlException: Cannot insert explicit value for identity column in table 'Categories' when IDENTITY_INSERT is set to OFF ASP.NET Core 2.1
[英]Cannot insert explicit value for identity column in TABLE when IDENTITY_INSERT is set to OFF; .NET Core 2.1
我正在嘗試在EF Core中克隆實體。 據我了解,我需要檢索它們AsNoTracking,然后重新添加它們,但是當我收到錯誤消息時:
當IDENTITY_INSERT設置為OFF時,無法在“練習”中為身份列插入顯式值;
我向ID添加了數據批注: [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
,但仍然遇到相同的錯誤。
這是我的代碼:
public class Exercise : Entity
{
public Exercise()
{
Sets = new HashSet<Set>();
}
public DateTime Date { get; set; }
public int MuscleGroupId {get;set;}
public int MesoId { get; set; }
public ICollection<Set> Sets { get; set; }
public void AddSet(Set set)
{
Sets.Add(set);
}
}
這是我的Entity代碼,我設置了一個注釋來告訴EF Core ID是數據庫生成的:
public class Entity
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
}
這是克隆實體的代碼:
var exercises = _context.Exercises.AsNoTracking().Include(y => y.Sets)
.Where(x => x.MesoId == mesoId && x.Date == fromDate);
foreach (var exercise in exercises)
{
exercise.Date = toDate;
_context.Exercises.Add(exercise);
}
await _context.SaveChangesAsync();
您不能將值存儲到數據庫的“標識”列中,因為該值由數據庫本身管理。
當“克隆”您的練習記錄時,您需要設置Id=0
以便在插入新行時數據庫將為其創建Identity值,例如:
foreach (var exercise in exercises)
{
exercise.Date = toDate;
exercise.Id = 0; //<<--This is important!
_context.Exercises.Add(exercise);
}
await _context.SaveChangesAsync();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.