我试图在我的程序中保存联系人,该程序是C#中的简单电话簿,并且我使用linq和Entity Framework,并且当我想添加或更改任何数据时遇到运行时错误
当IDENTITY_INSERT设置为OFF时,无法为表“联系人”中的标识列插入显式值。
这是我的insert
(添加)代码,另一方面,我不想在主键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();
}
}