2014-02-05 166 views
0

[增订]中的对象的图形替换单一实例对象的多个实例

我使用EF code first,在我的情况下,我不得不从DbContext断开我POCO s,而当我想保存更改为DB,将断开的POCO s(通过附加根对象)添加到DbContex t,但在我想要保存的对象图中,可能是具有相同键的实体的多个实例。 对于examle:

Order1 
| 
OrderLine1-->Product1 //instance1 of product1 
| 
OrderLine2-->Product1 //instance2 of product1 

,所以我得到以下错误:

An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.

所以我想编写找到一种方法,在我ApplyChange()方法用一个实例来替换对象的重复的实例:

public void ApplyChanges<TEntity>(TEntity root) where TEntity : BaseEntity 
{ 
     _dbContext.Set<TEntity>().Add(root); 
     foreach (var entry in _dbContext.ChangeTracker 
     .Entries<BaseEntity>()) 
     { 
      if (FoundAnEntityWithSameKeyInDbContext<TEntity>(entry)) 
       UniqeSimilarEntities(entry); 
      else 
      { 
       .... 
      } 
     } 
} 

我写这段代码:

private bool FoundAnEntityWithSameKeyInDbContext<TEntity>(DbEntityEntry<BaseEntity> entry) where TEntity : BaseEntity 
{ 
     var tmp = _dbContext.ChangeTracker.Entries<BaseEntity>().Count(t => t.Entity.Id == entry.Entity.Id && t.Entity.Id != 0 && t.Entity.GetType() == entry.Entity.GetType()); 
     if (tmp > 1) 
      return true; 
     return false; 
    } 
private void UniqeSimilarEntities(DbEntityEntry<BaseEntity> entry) 
{ 
     var similarEntities = _dbContext.ChangeTracker.Entries<BaseEntity>() 
     .Where(
      t => 
       t.Entity.Id == entry.Entity.Id && t.Entity.Id != 0 && 
       t.Entity.GetType() == entry.Entity.GetType()).ToList(); 

     for (int i = 1; i < similarEntities.Count; i++) 
     { 
      _dbContext.Entry(similarEntities[i]).CurrentValues.SetValues(similarEntities[0]); 
      similarEntities[i].State= EntityState.Unchanged; 
     } 
} 

我所有的实体从BaseEntity类继承:

public class BaseEntity 
{ 
    public int Id {get; set;} 
    public States State { get; set; } 
    public bool MustDelete {get; set;} 
    ... 
} 

但是,当控制达到UniqeSimilarEntities方法行_dbContext.Entry(similarEntities[i]).CurrentValues.SetValues...我得到这个错误:

The entity type DbEntityEntry`1 is not part of the model for the current context.

有什么办法来代替重复的实体我的根对象中有一个实例?

回答

0

Imho你应该在附件之前不要复制。在伪代码:

List<Product> lp = new List<Product>(); 
foreach (var line in Order.Lines) { 
    Product p = lp.Where(x => x.Id == line.Product.Id).FirstOrDefault(); 
    if (p == null) { 
     lp.Add(p); 
    } else { 
     line.Product = p; 
    } 
} 
+0

订单,订单行,产品就是一个例子,我想unduplicate在我的根对象的对象(即它是从BaseEntity继承的对象)。我更新了帖子。 – Masoud