自动编号与实体框架 [英] Autonumber with Entity Framework

查看:358
本文介绍了自动编号与实体框架的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要遍历对象的集合,他们都添加到表中。目标表有一个自动递增字段。如果我添加一个单一的对象是没有问题的。如果我想补充两个对象都为零的主键,实体框架失败。我可以手动指定主键,但尝试的EF整点是为了让生活更轻松不是更复杂。这里是code,并获得如下例外。

 的foreach(在接触与我联系联系)
{
    教师讲师= InstructorFromContact(接触);
    context.AddToInstructors(讲师);
}尝试
{
    context.SaveChanges();
}
赶上(异常前)
{
    Console.WriteLine(ex.ToString());
}

该错误是:


  

System.InvalidOperationException :到数据库的变化成功提交,但在更新时发生错误
  对象上下文。 ObjectContext中可能处于不一致的状态。
  内部异常消息:AcceptChanges的无法继续,因为
  对象的密钥值与另一个对象冲突
  ObjectStateManager。确保键值是唯一的前
  调用AcceptChanges的。在
  System.Data.Objects.ObjectContext.SaveChanges(SaveOptions选项)结果
  在System.Data.Objects.ObjectContext.SaveChanges()在
  DataMigration.Program.CopyInstructors()的
  C:\\项目\\ DataMigration \\的Program.cs:行52



解决方案

在您的SSDL为自动增量字段设置StoreGeneratedPattern属性身份。它应该帮助。

I want to loop through a collection of objects and add them all to a table. The destination table has an auto-increment field. If I add a single object there is no problem. If I add two objects both with the primary key of zero, the entity framework fails. I can manually specify primary keys but the whole point of trying the EF was to make life easier not more complicated. Here is the code and the exception received follows.

foreach (Contact contact in contacts)
{               
    Instructor instructor = InstructorFromContact(contact);             
    context.AddToInstructors(instructor);               
}

try
{                   
    context.SaveChanges();                  
}
catch (Exception ex)
{
    Console.WriteLine(ex.ToString());
}

The error is:

System.InvalidOperationException: The changes to the database were committed successfully, but an error occurred while updating the object context. The ObjectContext might be in an inconsistent state. Inner exception message: AcceptChanges cannot continue because the object's key values conflict with another object in the ObjectStateManager. Make sure that the key values are unique before calling AcceptChanges. at System.Data.Objects.ObjectContext.SaveChanges(SaveOptions options)
at System.Data.Objects.ObjectContext.SaveChanges() at DataMigration.Program.CopyInstructors() in C:\Projects\DataMigration\Program.cs:line 52

解决方案

Set the StoreGeneratedPattern attribute to "Identity" in your SSDL for the autoincrement field. It should help.

这篇关于自动编号与实体框架的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆