2

我正在使用的对象图基本上是:

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 我正在苦苦挣扎。

有任何想法吗?

4

1 回答 1

2

GraphDiff 基本上区分了两种关系:拥有关联拥有可以被解释为“成为的一部分”,这意味着任何拥有的东西都将与其所有者一起插入/更新/删除。GraphDiff 处理的另一种关系是关联的,这意味着在更新图形时,GraphDiff 只更改与实体的关系,而不是关联实体本身。

回到您的场景:您不想要重复或实体,而Technology只是它们的组合,所以重复就可以了。要使用 GraphDiff 对此进行建模,您告诉它将其视为a (由 a拥有)和的一部分,并将其视为a 的关联。这是这样映射的:CategoryCompetencySkillsSkillsSkillsResourceResourceTechnologyCategoryCompetencySkill

// 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();
}
于 2014-03-26T23:20:10.997 回答