微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – {“当IDENTITY_INSERT设置为OFF时,无法在表’Cantact’中为标识列插入显式值.”}

我正试图在我的程序中保存一个联系人,这是一个简单的C#电话簿,我正在使用 linq&实体框架&当我想添加或更改任何数据时,我得到运行时错误

Cannot insert explicit value for identity column in table ‘Contact’ when IDENTITY_INSERT is set to OFF.

这是我的插入(添加)代码,另一方面,我不想在我的主键中添加任何数据,这是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();
         }
    }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐