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

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

问题描述

我想遍历一组对象并将它们全部添加到表中.目标表有一个自增字段.如果我添加单个对象就没有问题.如果我添加两个主键为零的对象,实体框架将失败.我可以手动指定主键,但尝试 EF 的重点是让生活更轻松而不是更复杂.这是代码,收到的异常如下.

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());
}

错误是:

System.InvalidOperationException:已成功提交对数据库的更改,但更新数据库时发生错误对象上下文.ObjectContext 可能处于不一致的状态.内部异常消息:AcceptChanges 无法继续,因为对象的键值与该对象中的另一个对象冲突对象状态管理器.之前确保键值是唯一的调用 AcceptChanges.在System.Data.Objects.ObjectContext.SaveChanges(SaveOptions 选项)
在 System.Data.Objects.ObjectContext.SaveChanges() 在DataMigration.Program.CopyInstructors() 中C:ProjectsDataMigrationProgram.cs:line 52

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:ProjectsDataMigrationProgram.cs:line 52

推荐答案

在您的 SSDL 中为自动增量字段将 StoreGeneratedPattern 属性设置为Identity".应该会有所帮助.

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

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

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