【问题标题】:Manage detached entity with Entity Framework使用 Entity Framework 管理分离的实体
【发布时间】:2014-08-16 04:53:00
【问题描述】:

我的应用程序读取一个 XML 文件并创建一个 PatientDto,我在方法 CreatePatient(PatientDto patient) 中使用它

此方法将PatientDto 映射 到Patient 并将其存储在实体框架中。通过映射,我的意思是创建一个新的Patient,其值为PatientDto

这个病人写如下:

public class PatientDto
{
    public string Name { get; set; }
    public IEnumerable<DietDto> Diets { get; set; }
}

internal class Patient
{ 
    public Patient(PatientDto dto)
    {
        this.Name = dto.Name;
        this.Diets = this.BuildDiets(dto.Diets);
    }
    public string Name { get; set; }
    public IEnumerable<Diet> Diets { get; set; }
}

一个Diet 有一个Week 的列表,它有一个Day 的列表,它有一个Meal 的列表,还有一个Ingredient 的列表。

当我创建一个新患者时,图表的所有对象都是新的(也就是说它们应该存储在数据库中)但是成分。成分已存在于数据库中。

由于映射,所有的成分都是不同的实例(即使它们具有相同的业务含义。即具有相同 ID 的两个成分具有不同的实例)。

当我执行我的代码时,我遇到了一个异常:

A duplicate value cannot be inserted into a unique index. [ Table name = Ingredients,Constraint name = PK_dbo.Ingredients ]

我发现的快速修复是这个:

foreach (var diet in patient.Diets)
    foreach (var week in diet.Weeks)
        foreach (var day in week.Days)
            foreach (var recipe in day.Meals)
                for (int i = 0; i < recipe.Recipe.Ingredients.Count; i++)
                {
                    recipe.Recipe.Ingredients[i] = (from igt in this.Context.Ingredients
                                                    where igt.Id == recipe.Recipe.Ingredients[i].Id
                                                    select igt).Single();
                }

但是,它并不是真正可读的,并且循环中的循环中的循环,在...中不是我所说的优化代码。

还有其他正确的方法吗?

【问题讨论】:

    标签: c#-4.0 entity-framework-4


    【解决方案1】:

    您必须使用从上下文中检索到的实际成分对象,以便 EF 正确更新数据库。它看起来你需要做一些循环来为对象图中的所有实体做这件事。在这种情况下,您应该做的是减少数据库访问量,也许这段代码会在这个方向上帮助您。

    var ingredientIds = recipe.Recipe.Ingredients.Select(ingredient => ingredient.Id).ToList();
    List<Ingredients> dbIngredients = this.Context.Ingredients.Where(ingredient => ingredientIds.Contains(ingredient.Id)).ToList();
    recipe.Recipe.Ingredients = dbIngredients;
    

    任何努力使用 EF 和相关实体更新对象图的人也应该查看GraphDiff

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-08-06
      • 2013-12-25
      • 1970-01-01
      • 2012-01-16
      • 2012-08-23
      • 2020-07-30
      • 1970-01-01
      相关资源
      最近更新 更多