【问题标题】:General way for managing duplicate entities in different parent entities管理不同父实体中重复实体的一般方法
【发布时间】:2015-05-20 11:46:26
【问题描述】:

我有这样的模型:

public class EntityFirst
{
    public int Id { get; set; }
    public int EntityThirdId { get; set; }

    public virtual EntityThird { get; set; }
}

public class EntitySecond
{
    public int Id { get; set; }
    public int EntityThirdId { get; set; }

    public virtual EntityThird { get; set; }
}

public class EntityThird 
{
    public int Id { get; set; }

    // These columns are unique together
    public int DocumentType { get; set; }
    public string DocumentNumber { get; set; }
}

假设我必须将 EntityFirstEntitySecond 对象插入数据库。但是EntityThird 有一些独特性,DocumentTypeDocumentNumber 在一起是独特的。所以,在调用SaveChanges 之前,我正在检查数据库中是否存在这样的EntityThird。如果它存在,那么我将其设置为Id 并设置为父级的EntityThirdId,当然还要将此实体的状态更改为Detached

到目前为止,一切都很好。

问题是:

如果EntityFirstEntitySecond 具有EntityThird 对象,它们都具有相同的DocumentTypeDocumentNumber 会怎样。在这种情况下,我必须只将其中一个插入数据库并获取新插入的对象Id。然后将两个实体中的EntityThirdId 值设置为此Id

我该如何解决这个问题?

【问题讨论】:

    标签: c# .net entity-framework entity-framework-5


    【解决方案1】:

    我的问题已经解决了。

    目前,我假设堆中有两个实体,当然还有两个对象。因此,EF 试图将两个实体都插入数据库。我曾想过,如果这两个实体都引用同一个地址,那么 EF 将只插入其中一个。当然,我还需要创建另一个或多个实体(如果有超过 2 个相同的实体) Detached.

    而且,这解决了我的问题。

    作为补充说明,我将分享部分代码,以便其他人可以使用:

    // Here I find all this type of entities which has Added state
    var addedEntities = context.Set<TEntity>()
                  .Local
                  .AsEnumerable();
    

    然后,我正在检查所有实体是否有任何其他相同的实体,或者您可以根据您的要求在此处使用GroupBy 等等

    // parent - This is an owner entity
    if (addedEntities.Count(x => ...) > 1)
    {
        parent.GetType()
              .GetProperty("MyTypeName")
              .SetValue(parent, addedEntities.LastOrDefault(...));
    
        // Detach your object here...
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-31
      • 2011-08-09
      • 1970-01-01
      • 2012-03-08
      • 1970-01-01
      • 2012-05-05
      • 1970-01-01
      • 2015-05-10
      相关资源
      最近更新 更多