使用Linq to Entities(EF)插入多个记录

时间:2010-02-17 13:02:26

标签: linq-to-entities records

我有一个可以包含多个记录的地图表(tblUserRoles)。当我只使用L2E插入一条记录时,它会保存,但是当尝试保存多条记录时,它会产生异常。我这样保存:

foreach (tblUserRoles u in InsertUserRole)
{   
     EntityHelperUtil.AddObject(context, "tblUserRoles", (IEntityWithRelationships)u);                            
}

context.SaveChanges();

我正在使用(http://bernhardelbl.spaces.live.com/blog/cns!DB54AE2C5D84DB78!238.entry)的EntityHelperUtil实用程序类 这是一个例外:

AttachSingleObject(System.Object, System.Data.Metadata.Edm.EntitySet, System.String)---An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.
   at System.Data.Objects.ObjectContext.AttachSingleObject(Object entity, EntitySet entitySet, String argumentName)
   at System.Data.Objects.DataClasses.RelatedEnd.AddEntityToObjectStateManager(IEntityWithRelationships entity, Boolean doAttach)
   at System.Data.Objects.DataClasses.RelatedEnd.AddGraphToObjectStateManager(IEntityWithRelationships entity, Boolean relationshipAlreadyExists, Boolean addRelationshipAsUnchanged, Boolean doAttach, HashSet`1 promotedEntityKeyRefs)
   at System.Data.Objects.DataClasses.RelatedEnd.IncludeEntity[U](U entity, Boolean addRelationshipAsUnchanged, Boolean doAttach, HashSet`1 promotedEntityKeyRefs)
   at System.Data.Objects.DataClasses.EntityCollection`1.Include(Boolean addRelationshipAsUnchanged, Boolean doAttach, HashSet`1 promotedEntityKeyRefs)
   at System.Data.Objects.DataClasses.RelationshipManager.AddRelatedEntitiesToObjectStateManager(Boolean doAttach)
   at System.Data.Objects.ObjectContext.AttachTo(String entitySetName, Object entity)
   at System.Data.Objects.ObjectContext.Attach(IEntityWithKey entity)
   at HealthSphereServices.EntityHelperUtil.AddRelationships(ObjectContext context, List`1 map) in E:\E_Drive data\ORB\ORB_Development\ControlRoom\ControlRoom\HealthSphereServices\EntityHelperUtil.cs:line 158

1 个答案:

答案 0 :(得分:1)

好像你有:

  1. 重复的,客户端生成的PK值,或
  2. 服务器生成的PK,在您的EDMX中未映射。因此,EF不会忽略新对象上的PK值。
  3. 如果没有看到你的模特,我不能说更多。