【发布时间】: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();
}
但是,它并不是真正可读的,并且循环中的循环中的循环,在...中不是我所说的优化代码。
还有其他正确的方法吗?
【问题讨论】: