实体框架6数据库首先有多对多的关系

时间:2014-03-03 03:41:19

标签: c# entity-framework many-to-many entity-framework-6 ef-database-first

我正在尝试EF6并试图利用多对多关系。

首先使用数据库是我的脚本化数据库。

CREATE TABLE [States] (
    Id int identity (1, 1) not null primary key,
    Name varchar(50) not null,
    Abbreviation varchar(2) not null
)
GO

CREATE TABLE Departments (
    Id int identity (1, 1) not null primary key,
    Name varchar(50),
)
GO

CREATE TABLE [Role] (
    Id int identity (1, 1) not null primary key,
    Name varchar(50)
)
GO

CREATE TABLE Employees (
    Id int identity (1, 1) not null primary key,
    FirstName varchar(50),
    LastName varchar(50),
    Email varchar(255),
    DepartmentId int constraint fk_Department_Id foreign key references Departments(Id)
)

GO

CREATE TABLE AssignedRoles (
    Id int identity (1, 1) not null primary key,
    EmployeeId int not null constraint fk_Employee_Id foreign key references Employees(Id),
    RoleId int not null constraint fk_Role_Id foreign key references [Role](Id),
)
GO

CREATE TABLE [Addresses] (
    Id int identity (1, 1) not null primary key,
    EmployeeId int not null,
    StreetAddress varchar(255),
    City varchar(55),
    StateId int not null,
    ZipCode varchar(10),
    CONSTRAINT fk_Employee_Id_Address foreign key (EmployeeId) REFERENCES [Employees](Id),
    CONSTRAINT fk_State_Id foreign key (StateId) REFERENCES [States](Id)
)
GO

我的代码:

public MicroOrmComparison.UI.Models.Employee Add(MicroOrmComparison.UI.Models.Employee employee)
{
    var employeeToInsert = AutoMapper.Mapper.Map<MicroOrmComparison.UI.Models.Employee, Employee>(employee);
    using (var db = new EmployeeDb())
    {
        db.Employees.AddOrUpdate(employeeToInsert);
        if (employeeToInsert.Addresses != null)
        {
            foreach (var address in employeeToInsert.Addresses)
            {
                db.Addresses.AddOrUpdate(address);
            }
        }
        if (employeeToInsert.Roles != null)
        {
            foreach (var role in employeeToInsert.Roles)
            {
                role.Employees.Add(employeeToInsert);
                db.Roles.AddOrUpdate(role);
                db.Employees.AddOrUpdate(employeeToInsert);
            }
        }
        db.SaveChanges();
        employee.Id = employeeToInsert.Id;
    }
    return employee;
}

首先从EF6数据库生成员工

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated from a template.
//
//     Manual changes to this file may cause unexpected behavior in your application.
//     Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace EntityFramework.DataLayer
{
    using System;
    using System.Collections.Generic;

    public partial class Employee
    {
        public Employee()
        {
            this.Addresses = new HashSet<Address>();
            this.Roles = new HashSet<Role>();
        }

        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Email { get; set; }
        public Nullable<int> DepartmentId { get; set; }

        public virtual ICollection<Address> Addresses { get; set; }
        public virtual Department Department { get; set; }
        public virtual ICollection<Role> Roles { get; set; }
    }
}

生成角色代码

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated from a template.
//
//     Manual changes to this file may cause unexpected behavior in your application.
//     Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace EntityFramework.DataLayer
{
    using System;
    using System.Collections.Generic;

    public partial class Role
    {
        public Role()
        {
            this.Employees = new HashSet<Employee>();
        }

        public int Id { get; set; }
        public string Name { get; set; }

        public virtual ICollection<Employee> Employees { get; set; }
    }
}

失败的罪恶测试

        [Test]
    public void ShouldAddRolesToUser()
    {
        //Arrange
        var testUserId = InsertUserToBeModified();
        //Act
        var employee = _employeeRepository.GetFullEmployeeInfo(testUserId);
        employee.Roles.Add(new MicroOrmComparison.UI.Models.Role
        {
            Id = 3,
            Name = "Supervisor"
        });
        _employeeRepository.Save(employee);
        //Assert
        var result = _employeeRepository.GetFullEmployeeInfo(testUserId);
        result.Roles.Count().Should().Be(1);
        result.Roles.First().Id.Should().Be(3);
        //Cleanup
        _employeeRepository.Remove(testUserId);
    }

测试表明result.Roles.Count()为0。

我的问题是尝试添加到连接表AssignedRoles。我已经在角色块中的foreach中尝试了多个插入但仍然没有运气。我在这个网站内搜索但仍然没有运气。我一直在使用Micro ORM,这就是为什么连接表的魔力让我大吃一惊。任何帮助将不胜感激。如果需要,我有更多的代码,让我知道代码不清楚。

当我在foreach循环中调试时,它不会添加到连接表中。帮助

1 个答案:

答案 0 :(得分:1)

修改

您缺少AssignedRoles表格。我将.edmx添加到我的项目中,我有了这个实体AssignedRole。尝试重新创建您的edmx。

旧答案(代码优先):

我刚试过使用你的数据库结构,一切正常。

EmployeeDbdb = new EmployeeDb();

  var empl = new Employee
        {
            FirstName = "Test",
            LastName = "demo",
            Email = "aa@aaa.com"
        };

        var role = new Role
        {
            Name = "Role1"
        };

        db.Roles.AddOrUpdate(role);

        db.Employees.AddOrUpdate(empl);
        db.SaveChanges();


        db.AssignedRoles.AddOrUpdate(new AssignedRole
        {
            EmployeeId = empl.Id,
            RoleId = role.Id
        });

        db.SaveChanges();

OR:

EmployeeDbdb = new EmployeeDb();
var empl = new Employee
{
      FirstName = "Test",
      LastName = "demo",
      Email = "aa@aaa.com"
};

var role = new Role
{
    Name = "Role1"
};
db.Roles.AddOrUpdate(role);
db.Employees.AddOrUpdate(empl);
db.AssignedRoles.AddOrUpdate(new AssignedRole
{
      Role = role,
      Employee = empl
});
db.SaveChanges();