c# – {“当IDENTITY_INSERT设置为OFF时,无法在表’Cantact’中
发布时间:2020-12-15 20:56:37 所属栏目:百科 来源:网络整理
导读:我正试图在我的程序中保存一个联系人,这是一个简单的C#电话簿,我正在使用 linq实体框架当我想添加或更改任何数据时,我得到运行时错误 Cannot insert explicit value for identity column in table ‘Contact’ when IDENTITY_INSERT is set to OFF. 这是我的
我正试图在我的程序中保存一个联系人,这是一个简单的C#电话簿,我正在使用
linq&实体框架&当我想添加或更改任何数据时,我得到运行时错误
这是我的插入(添加)代码,另一方面,我不想在我的主键中添加任何数据,这是ID,我想将它留给我的SQL Server. 谢谢大家的帮助 public void Save() { using (var Contex = new Phone_BookEntities1()) { var p = from c in Contex.Cantacts where c.Cantact1 == Name select new { c.Cantact1,c.Number }; if (!p.Any()) { Ref_Cantact = new Cantact(); Ref_Cantact.Cantact1 = Name; Ref_Cantact.Number = Num; Contex.Cantacts.Add(Ref_Cantact); Contex.SaveChanges(); } } } 编辑 public partial class Cantact { public string Cantact1 { get; set; } public string Number { get; set; } public int ID { get; set; } } 解决方法
你可以这样做;
public void Save(string Name,string Num) { using(var context = new Phone_BookEntities1()) { var existingContacts = Context.Cantacts.Where( c=>c.Cantact1 == Name); //there can be many contacts with the same name. Use FirstOrDefault and also improve the filtering criteria if(existingContacts.Any()) { foreach(var contact in existingContacts) { contact.Number = Num; } }else { var Ref_Cantact = new Cantact(){Cantact1 = Name,Number = Num}; context.Cantacts.Add(Ref_Cantact); } Contex.SaveChanges(); } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |