关于Entity Framework中的Attached报错相关解决方案的总结

简介:

关于Entity Framework中的Attached报错的问题,我这里分为以下几种类型,每种类型我都给出相应的解决方案,希望能给大家带来一些的帮助,当然作为读者的您如果觉得有不同的意见或更好的方法,欢迎一起探讨!

1.单个实体对象在进行改删时出现Attached报错,解决方案,请参见:

http://www.cnblogs.com/zuowj/p/4523075.html

http://www.cnblogs.com/scy251147/p/3688844.html

原理:清除context上本地缓存的与之相关联的实体对象

2.单个实体对象在进行改删时,其关联的其它实体对象属性(即:导航属性)出现Attached报错,解决方案,请参见:

http://www.cnblogs.com/zuowj/p/4650781.html

原理:清除context上本地缓存所有的实体对象

3.多个不同的实体对象进行改删时,其自身出错或其关联的其它实体对象属性(即:导航属性)出现Attached报错,解决方案,如下:

首先增加一个用于清除指定实体对象的context上本地缓存方法,如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
public  void  DetachHoldingEntities( params  object [] entities)
{
     var  entries = context.ChangeTracker.Entries().Where(e => e.State != EntityState.Detached).ToList();
     if  (entities ==  null  && entities.Length <= 0)  return ;
     foreach  ( var  entity  in  entities)
     {
         var  entry = entries.SingleOrDefault(e => GetEntityKey(e.Entity).Equals(GetEntityKey(entity)));
         if  (entry !=  null  && entry.Entity !=  null )
         {
             entry.State = EntityState.Detached;
         }
     }
}
 
private  EntityKey GetEntityKey( object  entity)
{
     try
     {
         var  entityWrapper = entity.GetType().GetField( "_entityWrapper" ).GetValue(entity); //获取字段_entityWrapper的值
         var  entityWrapperType = entityWrapper.GetType(); //获取字段的类型
 
         var  entityKey = entityWrapperType.GetProperty( "EntityKey" ).GetValue(entityWrapper,  null ); //获取EntityKey属性的值
 
         return  (EntityKey)entityKey;
     }
     catch
     {
         return  null ;
     }
}

然后在进行改删前,调用上述清除方法清除指定的实体即可,示例代码如下:

1
2
ctx.DetachHoldingEntities(entity.TA_CWBankAccountInfo);
ctx.GetRepository<TA_CWTransferRequestInfo>().Update(entity);

 当然还有一个比较简单的方法来避免上述错误,那就是:使用原生的DbContext进行增、删操作,更改则由DbContext的自动跟踪来进行处理,对于不是从DbContext查到的实体对象,若需要参与增删改时,请先进行Attach操作,否则都是来自于DbContext的实体对象则不需要再进行Attach。

本文转自 梦在旅途 博客园博客,原文链接:http://www.cnblogs.com/zuowj/p/5088521.html  ,如需转载请自行联系原作者

相关文章
|
数据建模
SAP SEGW 里的 Entity Type 作用讲解
SAP SEGW 里的 Entity Type 作用讲解
157 0
SAP SEGW 里的 Entity Type 作用讲解
|
存储 开发框架 .NET
Entity Framework基础01
Entity Framework基础01
186 0
Entity Framework基础01
SAP S/4HANA key user tool extensibility原理
Reasons of different behavior in “UI and Reports” list
SAP S/4HANA key user tool extensibility原理
如何处理SAP CRM Web Service错误 - Virtual Interface Method XXXX not supported
如何处理SAP CRM Web Service错误 - Virtual Interface Method XXXX not supported
162 0
如何处理SAP CRM Web Service错误 - Virtual Interface Method XXXX not supported
filter operation implementation in SAP Gateway framework
Created by Wang, Jerry, last modified on Dec 30, 2015
filter operation implementation in SAP Gateway framework
|
数据库
Entity Framework 迁移
Entity Framework 迁移
104 0