【问题标题】:Why two records are inserted when i try to insert Employee object which has Manager of type Employee?为什么当我尝试插入具有 Employee 类型的 Manager 的 Employee 对象时会插入两条记录?
【发布时间】:2013-09-12 05:45:08
【问题描述】:

我有一个类:

public class Employee
{
    public int Id { get; set; }

    public string Name { get; set; }

    public virtual Employee Manager { get; set; }

    public virtual Department Deptartment { get; set; }
}

public class Department
{
    public int Id { get; set; }

    public string Name { get; set; }

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

在控制器中创建新员工的代码:此代码在 DB 中插入两条记录。

[HttpPost]
        public ActionResult Create(Employee employee)
        {
            if (ModelState.IsValid)
            {
                db.Employees.Add(employee);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(employee);
        }

我正在提供用于创建新员工的 MVC4 视图,其中用户输入员工姓名和 ManagerId。当我获得发布的 Employee 对象时,它具有由用户输入的 ID 的 Manager 对象。但是,对于该对象,其他详细信息(例如名称)为空,其中具有该 userId 的员工存在于数据库中。在数据库中插入员工记录时,应用程序正在插入两条记录(一条是用户输入的员工姓名,另一条是用户为该员工提供的经理 ID。对于发送,名称保存为空)。为什么要插入两条记录?

【问题讨论】:

  • Employee 表的主键是什么?只是身份证吗?

标签: c# asp.net-mvc-4 entity-framework-5


【解决方案1】:

如果您使用子对象Employee Manager 创建一个新员工,则必须重新加载该对象Employee,否则您将无法在数据库中获得经理的属性。仅添加 ID 是不够的。

例如你可以执行

public ActionResult Create(Employee employee)
{
    if (ModelState.IsValid)
    {
        employee.Manager = db.Employees.Find(employee.Manager.Id) // load Manager properties
        db.Employees.Add(employee);
        db.SaveChanges();
        return RedirectToAction("Index");
    }
    return View(employee);
}

所以这里发生的情况如下:在发布新的Employee 对象之前,您使用正确的属性重新加载Manager 对象。所以 Entity Framework 知道实体已经存在并且不为其创建新对象(如果 Id 已经存在)。

【讨论】:

  • 是不是有点多余。因为如果我分配 ManagerId 意味着它已经存在于表中。我可以指示 EF 不要为 MangerId 创建另一条记录吗?
  • 不,如果对象尚未加载,这不是多余的。但这取决于您的主键。如果 Id 是您在表 Employee 中唯一的主键,您甚至不应该能够插入具有相同 Id 的第二个条目。所以也许这取决于你的表结构。
猜你喜欢
  • 2018-04-21
  • 1970-01-01
  • 1970-01-01
  • 2015-10-24
  • 1970-01-01
  • 1970-01-01
  • 2018-06-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多