【问题标题】:Inserting data using one to many relationship in Entity Framework在实体框架中使用一对多关系插入数据
【发布时间】:2016-02-18 13:53:03
【问题描述】:

我的项目有问题。我在我的项目中首先使用实体​​框架代码。

问题是:我有两个模型,它们之间存在一对多关系。

员工模型:

{
    public int employeeId { get; set; }

    public string name { get; set; }

    public string surname { get; set; }

    public int tel_no { get; set; }

    public string fullname
    {
        get
        {
            return name + " " + surname;
        }
    }

    public virtual Department Department { get; set; }
    public virtual Manager Manager { get; set; }
}

部门模型:

{
    public int departmentId { get; set; }

    public string name { get; set; }

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

首先,我成功地将部门数据插入到部门表中。之后,我想将员工数据插入员工表。当我将员工数据插入相关表时,我也会从部门表中获取部门数据以建立员工和数据之间的关系。

但是当我点击保存按钮时,我从部门表中获取的数据正在再次插入到部门表中,并且部门表中有两个相同的数据。

这是我的看法:

<div class = "form-group">
        <label class = "control-label col-md-3"> Adı </label>

        <div class = "col-md-8">
            @Html.EditorFor(model => model.name, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.name, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        <label class="control-label col-md-3"> Soyadı </label>

        <div class="col-md-8">
            @Html.EditorFor(model => model.surname, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.surname, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        <label class="control-label col-md-3"> Telefon Numarası </label>

        <div class="col-md-8">
            @Html.EditorFor(model => model.tel_no, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.tel_no, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        <label class="control-label col-md-3"> Bölümü </label>

        <div class="col-md-8">
            @Html.DropDownListFor(model => model.Department.name, ViewBag.Departments as SelectList, new { @class = "form-control dropdown-toggle" })
            @Html.ValidationMessageFor(model => model.Department.name, "", new { @class = "text-danger" })
        </div>
    </div>
    <div class="form-group">
        <label class="control-label col-md-3"> Yöneticisi </label>

        <div class="col-md-8">
            @Html.DropDownListFor(model => model.Manager.fullname, ViewBag.Managers as SelectList, new { @class = "form-control dropdown-toggle" })
            @Html.ValidationMessageFor(model => model.Manager.fullname, "", new { @class = "text-danger" })
        </div>
    </div>

这里是控制器:

// GET: Admin/CreateEmployee
    public ActionResult CreateEmployee()
    {
        var nameOfManagers = (from manager in database.Employee select manager);
        var nameOfDepartments = (from department in database.Department select department);

        ViewBag.Managers = new SelectList(nameOfManagers, "fullname", "fullname");
        ViewBag.Departments = new SelectList(nameOfDepartments, "name", "name");

        return View();
    }

    // POST: Admin/CreateEmployee
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult CreateEmployee(Employee employee)
    {
        if(ModelState.IsValid)
        {
            if(employee.Manager != null)
            {
                String[] manager_info = employee.Manager.fullname.Split(' ');

                for (int i = 0; i < manager_info.Length - 1; i++)
                {
                    employee.Manager.name += manager_info[i] + " ";
                }

                employee.Manager.surname = manager_info[manager_info.Length - 1];
            }

            database.Employee.Add(employee);
            database.SaveChanges();

            return RedirectToAction("Index");
        }

        return View(employee);
    }

最后是运行项目的截图:

Showing of Department and Employee Table data

我无法解决这个问题。如果你帮助我,我很高兴。 谢谢你。

【问题讨论】:

  • 我看不到你从哪里得到你正在创建的员工的部门......并且,作为一个建议,调用你的 Get 方法 GetEmployee,所以你没有两个 CreateEmployee 做不同事情的方法。无论如何,一个常见的问题是添加一个未附加到相同(或任何)上下文的相关实体。

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


【解决方案1】:

问题是您实际上是在创建一个新部门。通过发布到Department.name,模型绑定器在Employee 上新建一个Department 实例,然后设置该实例的name 属性。但是,没有设置其他属性,例如,重要的是 id。因此,当您保存员工时,没有 id 的部门在 Entity Framework 中看起来是新的,它也会创建它。

应该做的是发布到Employee 上的属性,这不会导致创建Department 的实例。本质上,您有两个选择:

  1. 如果您在 Employee 上具有显式外键属性,例如 DepartmentId,则发布到 。如果填写了外键属性并且导航属性Department 为空,Entity Framework 将使用数据库中匹配DepartmentId 的部门回填。

  2. 如果您没有明确的外键属性,即您只有Department 属性并且依赖实体框架的基于约定的方法在表中自动创建一个列来跟踪该关系,那么您 必须使用视图模型。让我再说一遍:你绝对不能直接使用你的实体。您需要创建如下内容:

    public class EmployeeViewModel
    {
        // other employee properties you want to edit
    
        public int DepartmentId { get; set; }
    }
    

    然后,一旦您开始发布操作,您需要将此视图模型中的值映射到您的实际实体,即使用 DepartmentId 的发布值从数据库中查找正确的部门为您的员工设置Department 属性。

【讨论】:

  • 谢谢。我会在我的项目上尝试你的建议。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-24
相关资源
最近更新 更多