我正在处理的对象图基本上是:
public class Resource
{
public string Forename { get; set; }
public string Surname { get; set; }
public int EmployeeNumber { get; set; }
public ICollection<Skill> Skills { get; set; }
}
public class Skill
{
public int SkillId{get; private set;}
public Technology Technology { get; set; }
public SkillCategory Category { get; set; }
public SkillCompetency Competency { get; set; }
}通过选择现有技术、SkillCategory、SkillCompetency的组合,可以向用户添加新的技能。我一直在努力(但失败了!)使用GraphDiff防止EF试图添加复制技术、SkillCategory、SkillCompetency记录。这似乎应该是简单的使用GraphDiff,但作为一个相对的纽比EF夫妇,只有找到GraphDiff,我正在挣扎。
有什么想法吗?
发布于 2014-03-26 23:20:10
GraphDiff基本上区分了两种关系:拥有关系和关联关系。拥有可以解释为“是其中的一部分”,意思是拥有的任何东西都将与其所有者一起插入/更新/删除。GraphDiff处理的另一种关系是相关联的,这意味着在更新一个图时,GraphDiff只改变与而不是关联实体本身的关系。
回到您的场景:您不需要重复的Technology、Category或Competency实体,但是Skills只是这些实体的组合,所以复制Skills是可以的。要使用GraphDiff对此进行建模,您可以告诉它将Skills视为Resource (由Resource拥有)的一部分,而Technology、Category和Competency则视为Skill的关联。这个映射如下所示:
// these three entities are all managed separately and have already been saved elsewhere
Technology entityFrameworkCodeFirst;
Category objectRelationalMappers;
Competency notThatIncompetent;
using (DbContext context = new WhatEverYourContextIsNamed())
{
Resource developer = new Resource
{
Skills = new List<Skill>
{
new Skill
{
Technology = entityFrameworkCodeFirst,
Category = objectRelationalMappers,
Competency = notThatIncompetent,
}
}
};
context.UpdateGraph(developer,
map => map.OwnedCollection(r => r.Skills,
with => with.AssociatedEntity(skill => skill.Technology)
.AssociatedEntity(skill => skill.Category)
.AssociatedEntity(skill => skill.Competency)));
context.SaveChanges();
}https://stackoverflow.com/questions/22170439
复制相似问题