【发布时间】:2019-11-11 12:42:06
【问题描述】:
我正在创建一个用于费用跟踪的网站,当我发送一个新的 POST 请求调用 AddNew 方法来添加一个新条目时,我收到此错误:
SqlException:当 IDENTITY_INSERT 设置为 OFF 时,无法在表“Accounts”中插入标识列的显式值。当 IDENTITY_INSERT 设置为 OFF 时,无法为表“类别”中的标识列插入显式值。
public class Entry
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string Description { get; set; }
public decimal MoneyAmount { get; set; }
public virtual Account Account { get; set; }
public virtual Category Category { get; set; }
public string CreatedTimestamp { get; set; }
}
public class Account
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string Name { get; set; }
public virtual User User { get; set; }
//public byte[] BankApi { get; set; }
public decimal MoneyAmount { get; set; }
public string CreatedTimestamp { get; set; }
public virtual ICollection<Entry> Entries { get; set; }
}
public class Category
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string Name { get; set; }
public virtual EntryType EntryType { get; set; }
public virtual ICollection<Entry> Entries { get; set; }
}
public interface IEntryService
{
void AddNew(Entry entry);
}
public class EntryService : IEntryService
{
private DataContext _context;
public EntryService(DataContext context)
{
_context = context;
}
public void AddNew(Entry entry)
{
entry.CreatedTimestamp = DateTime.Now.ToString();
_context.Entries.Add(entry);
_context.SaveChanges();
}
}
这是我的邮递员要求:
ID == 1 的帐户和 ID == 1 的类别都已存在于各自的数据库中。
此外,当我向 Account 数据库中插入值时,其方法看起来与 AddNew 的条目完全相同,它可以正常工作。
有人知道这是怎么回事吗?
【问题讨论】:
-
你试过这个解决方案了吗:stackoverflow.com/questions/1334012/…
-
DatabaseGenerated.Identity 表示您将 PK 生成留给数据库。在添加条目之前尝试设置 entry.Id = 0。
-
@VidmantasBlazevicius 我将 entry.Id 设置为 0,但我得到了同样的错误。
-
这里有很多缺失的代码。该错误抱怨您为
Accounts和Categories实体设置了一个ID。错误在于您实例化并保存这两个对象而不是Entry。
标签: c# sql entity-framework asp.net-core-2.2