gpt4 book ai didi

c# - {"Cannot insert explicit value for identity column in table ' Cantact' 当 IDENTITY_INSERT 设置为 OFF 时。"}

转载 作者:行者123 更新时间:2023-11-30 12:57:36 33 4
gpt4 key购买 nike

我正在尝试在我的程序中保存一个联系人,这是一个简单的 C# 电话簿,我正在使用 linq 和 Entity Framework ,当我想添加或更改任何数据时,我遇到运行时错误

Cannot insert explicit value for identity column in table 'Contact' when IDENTITY_INSERT is set to 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();
}
}

关于c# - {"Cannot insert explicit value for identity column in table ' Cantact' 当 IDENTITY_INSERT 设置为 OFF 时。"},我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33645362/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com