将两个实体相互映射

时间:2020-10-07 08:26:51

标签: c# asp.net entity-framework

我正在从事一个图书馆项目,我有一个名为“ Employees” 的数据库表,该表具有多个列,例如 ManagerId EmployeeId 。我想将 ManagerId 映射到 EmployeeId

因此,想法是,如果有一个名为“ Max”的员工和一个名为“ Bob”的经理,我希望Max拥有Bobs ID,以表明Max的经理是Bob。

希望我很清楚...我试图找出解决方法。

EmployeeController

 public ActionResult Create()
    {


        ViewBag.Employees = new SelectList(db.Category, "Id", "Employees");
        return View();
    }

    // POST: Employees/Create
    // To protect from overposting attacks, enable the specific properties you want to bind to, for 
    // more details see https://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "Id,FirstName,LastName,Salary,IsCEO,IsManager,ManagerId")] Employees employees)
    {
       

        if (ModelState.IsValid)
        {
            //Checks if there is a ceo
            var ceo = db.Employees.FirstOrDefault(x => x.IsCEO == employees.IsCEO);
            if (ceo == null)
            {
                db.Employees.Add(employees);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            else
            {
                // Informing the user about the problem
                ViewBag.ErrorMessage3 = "There is already a CEO in the database! You cannot create a second one!";
            }
        }

        return View(employees);
    }

希望我能使自己更清楚,请让我知道是否必须编辑问题以使其更清楚。

致谢

picture for Adrian

2 个答案:

答案 0 :(得分:0)

您需要使用Forengkeys来推荐员工

首先:

  1. 员工和经理都是员工,因此您只需要一个数据库表
  2. 要将一个用户引用到另一个用户(员工经理),您需要一个具有ID的表
  3. 要正确执行此操作并获得良好的性能,您将需要将员工表(第1点)中的ID引用到经理-外键和雇员-外键(第2点)

如果您从未听说过此消息,可能听起来很不可思议。这里有一个数据库示例和一些测试数据。如果您有任何疑问,请告诉我

DROP DATABASE IF EXISTS myDatabase;
CREATE DATABASE myDatabase character set UTF8mb4 collate utf8mb4_bin;
USE myDatabase;

create table `Employees`(
ID int AUTO_INCREMENT PRIMARY KEY NOT NULL, 
`name` varchar(20) not null,
`surname` varchar(20) not null,       
created_at timestamp default current_timestamp,
last_modifed timestamp on UPDATE current_timestamp default current_timestamp
);

create table `EmployeeManager`(
ID int AUTO_INCREMENT PRIMARY KEY NOT NULL,    
FK_Manager int not null,
FK_Employee int not null,
created_at timestamp default current_timestamp,
last_modifed timestamp on UPDATE current_timestamp default current_timestamp
);

ALTER TABLE `EmployeeManager` ADD FOREIGN KEY (FK_Manager) REFERENCES `Employees`(ID);
ALTER TABLE `EmployeeManager` ADD FOREIGN KEY (FK_Employee) REFERENCES `Employees`(ID);

INSERT INTO `Employees` (`name`, `surname`)  VALUES ('Max', 'Muller');
INSERT INTO `Employees` (`name`, `surname`)  VALUES ('Bob', 'Smith');

INSERT INTO `EmployeeManager` (`FK_Manager`, `FK_Employee`)  
VALUES (
    (SELECT ID FROM `Employees` WHERE `name` = 'Bob' AND `surname` = 'Smith'),
    (SELECT ID FROM `Employees` WHERE `name` = 'Max' AND `surname` = 'Muller'));

答案 1 :(得分:0)

如果您希望每个Employee都有一个Manager,则需要向Foreign Key类中添加一个Employee

员工类别:

public class Employee
{
    [Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] // For autoincrement
    public int EmployeeId { get; set; }
    [Required]
    [Index]
    public int ManagerId { get; set; } // Manager ID Foreign Key
    [Required]

    // Add other Database Values here
}

如果现在要添加新的Employee,则需要先获取Manager,然后将其插入Employee

例如,您可以使用名称或类似名称来获取Manager

通过名称获取经理:

int mID = 0;
string mName = "Test";

using(ForumDbContext context = new ForumDbContext())
{
    foreach(Manager manager in context.Managers
        .SqlQuery("SELECT * FROM Managers WHERE Name = '" + mName + "'").ToList<Manager>())
    {
        mID = manager.M_ID;
    }
}

我们现在可以使用此mID来创建一个新的Employee,而相应的Manager就是我们要搜索的人。

创建新员工:

Employee empl = new Employee
{
    ManagerId = mID,
    // Add other Database Values here
};

using(var context = new ForumDbContext())
{
    context.Employees.Add(empl);
    context.SaveChanges();
}