[英]{“Cannot insert explicit value for identity column in table 'Cantact' when IDENTITY_INSERT is set to OFF.”}
I'm trying to save a contact in my program which is a simple phone book in C# and I'm using linq & Entity Framework & when I want to add or change any data I get a run time error 我正在尝试在我的程序中保存一个联系人,这是一个简单的C#电话簿,我正在使用linq和实体框架,当我想添加或更改任何数据时,我得到一个运行时错误
Cannot insert explicit value for identity column in table 'Contact' when IDENTITY_INSERT is set to OFF. 当IDENTITY_INSERT设置为OFF时,无法在表'Contact'中为identity列插入显式值。
Here's my insert
(add) code, on the other hand I don't want to add any data in my primary key which is ID and I want to leave it to my SQL Server. 这是我的insert
(添加)代码,另一方面,我不想在我的主键中添加任何数据,这是ID,我想将它留给我的SQL Server。
Thank you all for helping me 谢谢大家的帮助
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();
}
}
}
EDIT 编辑
public partial class Cantact
{
public string Cantact1 { get; set; }
public string Number { get; set; }
public int ID { get; set; }
}
You may do this; 你可以这样做;
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();
}
}
you can try this: this will wrap all calls in a transaction, therefore setting identity insert on for the insert statement (Created by EF when calling Add+SaveChanges). 您可以尝试这样做:这将包装事务中的所有调用,因此为insert语句设置标识插入(在调用Add + SaveChanges时由EF创建)。
if (!p.Any())
{
Ref_Cantact = new Cantact();
Ref_Cantact.Cantact1 = Name;
Ref_Cantact.Number = Num;
using(var trans=Contex.Database.BeginTransaction())
{
Contex.Database.ExecuteSqlStatement("SET IDENTITY_INSERT Contact ON;");
Contex.Cantacts.Add(Ref_Cantact);
Contex.SaveChanges();
trans.Commit();
}
}
EDIT: Another possibility would be setting AutoIncrement (DatabaseGeneratedOption.Identity) off, using (in your modelbuilder in context class (or whereever)): 编辑:另一种可能性是使用(在上下文类(或whereever)中的模型构建器中)关闭AutoIncrement(DatabaseGeneratedOption.Identity):
modelBuilder.Entity<Cantacts>().Property(x=>x.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
我需要在模型中更新我的.edmx类
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.