1

Ситуация: Есть таблицы Employee, Department и связывающая таблица Employee_Department

Employee:

 [DataContract(IsReference=true)]
    public partial class Employee
    {
        public Employee()
        {
            this.DaySchedules = new HashSet<DaySchedule>().ToList();
            this.EmployeeRoyalties = new HashSet<EmployeeRoyalty>().ToList();
            this.EmployeeRoyaltyRules = new HashSet<EmployeeRoyaltyRule>().ToList();
            this.Orders = new HashSet<Order>().ToList();
            this.Departments = new HashSet<Department>().ToList();
            this.Specialities = new HashSet<Speciality>().ToList();
            this.UIs = new HashSet<UI>().ToList();
        }

        [DataMember]
    public int EmployeeID { get; set; }
        [DataMember]
    public string FirstName { get; set; }
        [DataMember]
    public string SecondName { get; set; }
        [DataMember]
    public string ThirdName { get; set; }
        [DataMember]
    public string Login { get; set; }
        [DataMember]
    public string Password { get; set; }
        [DataMember]
    public string Comment { get; set; }
        [DataMember]
    public bool isActive { get; set; }

        [DataMember]
    public virtual List<DaySchedule> DaySchedules { get; set; }
        [DataMember]
    public virtual List<EmployeeRoyalty> EmployeeRoyalties { get; set; }
        [DataMember]
    public virtual List<EmployeeRoyaltyRule> EmployeeRoyaltyRules { get; set; }
        [DataMember]
    public virtual List<Order> Orders { get; set; }
        [DataMember]
    public virtual List<Department> Departments { get; set; }
        [DataMember]
    public virtual List<Speciality> Specialities { get; set; }
        [DataMember]
    public virtual List<UI> UIs { get; set; }
    }

Department:

  [DataContract(IsReference=true)]
    public partial class Department
    {
        public Department()
        {
            this.Services = new HashSet<Service>().ToList();
            this.Employees = new HashSet<Employee>().ToList();
        }

        [DataMember]
    public int DepartmentID { get; set; }
        [DataMember]
    public string Name { get; set; }
        [DataMember]
    public bool isActive { get; set; }

        [DataMember]
    public virtual List<Service> Services { get; set; }
        [DataMember]
    public virtual List<Employee> Employees { get; set; }
    }

Метод добавления Employee:

  public Employee AddEmployee(Employee employee)
        {
          try
            {
             Employee emp= Data.Context.Employee.Add(employee);
             Data.Context.SaveChanges();
             return emp;
            }
            catch(Exception ex)
            {
               //обработчик
            }
        }

Метод обновления Employee:

     public void UpdateEmployee(Employee employee)
            {
               Employee tmp = Data.Context.Employee.Include("Departments").Single(o=>o.EmployeeID==employee.EmployeeID);
                if (tmp != null)
                {
                    try
                    {
                  Data.Context.Entry(tmp).CurrentValues.SetValues(employee);
                       Data.Context.SaveChanges();
                    }
                    catch (Exception ex)
                    {
                      //Обработчик
                    }
                }
            }

Проблема: Не могу добиться, чтобы при добавлении\обновлении записи Employee, содержащей один или более записей в Departments, в связующей таблице Employee_Departments средствами EF создавались\изменялись\удалялись все связующие записи. Наибольшего, чего мне удалось добиться - это создание при добавлении Employee новых записей в таблице Departments, даже если таковые записи уже существовали (дублирование). При этом в связующей таблице образовывались связки на дублированные отделы, что неправильно - связки должны образовываться к существующим отделам.

Вопрос: Как средствами Entity Framework организовать добавление\обновление записи, имеющей связку многие ко многим в свете описанной ситуации?

UPD:

Добился работы модифицировав UpdateEmployee следующим образом:

...
   Employee tmp = Data.Context.Employee.Include("Departments").Single(o=>o.EmployeeID==employee.EmployeeID);


      if (tmp != null)
                {
                    try
                    {
                        Data.Context.Entry(tmp).CurrentValues.SetValues(employee);
                        foreach (Department dep in employee.Departments)
                        {
                            Department d = Data.Context.Department.Single(o => o.DepartmentID == dep.DepartmentID);
                            if (d != null)
                            {
                                tmp.Departments.Add(d);
                            }

                        }
                        Data.Context.SaveChanges();
                     ...

Но мне не нравится это решение, поскольку мне приходится доказывать EF, что "я не жираф", повторно запрашивая по DepartmentID все экземпляры Department, которые и без того уже полностью содержаться в передаваемом Employee.Departments.

1 ответ 1

1

Вместо добивания deparment-ов по одному можно попробовать перебросить сразу все значения:

var entry = Data.Context.Entry(tmp);
var departments = entry.Collection("Departments");
departments.Load();
departments.CurrentValue = employee.Departments;

на enSO недавно пробегал похожий вопрос, с генерик-решением:

public virtual void Update(T updatedObject, int key, params string[] navigationProperties) {
    if (updatedObject == null) {
        return;
    }

    using (var databaseContext = new U()) {
        databaseContext.Database.Log = Console.Write;

        T foundEntity = databaseContext.Set<T>().Find(key);
        var entry = databaseContext.Entry(foundEntity);
        entry.CurrentValues.SetValues(updatedObject);                
        foreach (var prop in navigationProperties) {
            var collection  = entry.Collection(prop);
            collection.Load();
            collection.CurrentValue = typeof(T).GetProperty(prop).GetValue(updatedObject);
        }
        databaseContext.SaveChanges();
    }
}

вариант с заданием свойств через лямбды вместо перечисления по имени:

public virtual void Update(T updatedObject, int key, params Expression<Func<T, IEnumerable>>[] navigationProperties) {
    if (updatedObject == null) {
        return;
    }

    using (var databaseContext = new U()) {
        databaseContext.Database.Log = Console.Write;

        T foundEntity = databaseContext.Set<T>().Find(key);
        var entry = databaseContext.Entry(foundEntity);
        entry.CurrentValues.SetValues(updatedObject);
        foreach (var prop in navigationProperties) {
            string memberName;
            var member = prop.Body as MemberExpression;
            if (member != null)
                memberName = member.Member.Name;
            else throw new Exception("One of the navigationProperties is not a member access expression");
            var collection = entry.Collection(memberName);
            collection.Load();
            collection.CurrentValue = typeof (T).GetProperty(memberName).GetValue(updatedObject);
        }
        databaseContext.SaveChanges();
    }
}

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.