Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/entity-framework/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 用对象图中的单个实例替换对象的多个实例_C#_Entity Framework_Ef Code First_Dbcontext - Fatal编程技术网

C# 用对象图中的单个实例替换对象的多个实例

C# 用对象图中的单个实例替换对象的多个实例,c#,entity-framework,ef-code-first,dbcontext,C#,Entity Framework,Ef Code First,Dbcontext,[更新] 我首先使用的是EF code,在我的例子中,我必须断开POCOs与DbContext的连接,当我想保存对DB的更改时,将断开连接的POCOs(通过附加根对象)附加到DbContext,但在我想保存的对象图中,可以是具有相同密钥的实体的多个实例。 例如: Order1 | OrderLine1-->Product1 //instance1 of product1 | OrderLine2-->Product1 //instance2 of product1 因此,我得到以下

[更新]

我首先使用的是
EF code
,在我的例子中,我必须断开
POCO
s与
DbContext
的连接,当我想保存对
DB
的更改时,将断开连接的
POCO
s(通过附加根对象)附加到
DbContex
t,但在我想保存的对象图中,可以是具有相同密钥的实体的多个实例。 例如:

Order1
|
OrderLine1-->Product1 //instance1 of product1
|
OrderLine2-->Product1 //instance2 of product1
因此,我得到以下错误:

ObjectStateManager中已存在具有相同密钥的对象。 ObjectStateManager无法跟踪具有相同属性的多个对象 钥匙

因此,我想编写一个方法,在我的
ApplyChange()
method中用一个实例查找并替换对象的重复实例:

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
            {
              ....  
            }
        }
}
但是,当控件到达
UniqeSimilarEntities
方法行
\u dbContext.Entry(similarEntities[i]).CurrentValues.SetValues…
时,我得到以下错误:

实体类型DbEntityEntry`1不是当前上下文的模型的一部分


有没有办法用我的根对象中的一个实例替换重复的实体?

在附加之前,您应该如何取消复制。在伪代码中:

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;
    }
}
List lp=new List();
foreach(Order.Lines中的var行){
Product p=lp.Where(x=>x.Id==line.Product.Id).FirstOrDefault();
if(p==null){
lp.Add(p);
}否则{
线积=p;
}
}

Order、OrderLine、Product就是一个例子,我想取消根对象中的对象的复制(它是从BaseEntity继承的对象)。我更新了帖子。
public class BaseEntity
{
  public int Id {get; set;}
  public States State { get; set; }
  public bool MustDelete {get; set;} 
  ... 
}
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;
    }
}