我正在使用的对象图基本上是:
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; }
}
通过选择现有技术,技能类别,技能能力的组合,可以向用户添加一项新技能。我一直在尝试(并且失败!)使用GraphDiff来防止EF尝试添加重复的Technology,SkillCategory,SkillCompetency记录。
使用GraphDiff似乎很容易实现,但是对于EF夫妇来说,这是一个相对较新的事物,仅发现我正在苦苦挣扎的GraphDiff。
有任何想法吗?
最佳答案
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();
}
关于c# - 如何使用GraphDiff更新表达式树,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22170439/