c# - 使用 MVC 5 和 Entity Framework 下拉关联实体

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

我正在使用 MVC 5 和 Entity Framework 。我有 2 个实体,一个 Person 和一个 PersonType。我在它们之间创建了一个关联,以便 Person 具有 PersonType 属性:

namespace Test.Models
{
    using System;
    using System.Collections.Generic;

    public partial class Person
    {
        public int PersonId { get; set; }
        public virtual PersonType personType { get; set; }
    }
}

此代码由实体数据模型 (.edmx) 生成。

在 Controller 中,我将所有 PersonType 添加到 ViewBag 中,以便可以将它们添加到页面中的下拉控件中:

ViewBag.PersonTypeList = new SelectList(db.PersonTypes, "Id", "Description");

页面的模型设置为“Person”并包含一个下拉列表:

<div class="form-group">
    @Html.LabelFor(model => model.personType, "Person Type", htmlAttributes: new { @class = "control-label col-md-4" })
    <div class="col-md-8">
        @Html.DropDownListFor(model => model.personType.Id, ViewBag.PersonTypeList as SelectList, new { htmlAttributes = new { @class = "form-control" } })
        @Html.ValidationMessageFor(model => model.personType.Id, "", new { @class = "text-danger" })
    </div>
</div>

这似乎工作正常,但是当涉及到保存 Person 时,它似乎试图使用我选择的 Id 创建一个新的 PersonType,而不是简单地引用 PersonType 表中已经存在的 ID?我这样做错了吗?非常感谢

最佳答案

如果您使用 .edmx 文件设置关系,您还应该获得 FK 属性,例如myPerson.PersonType_Id(通常名称为{classname}_{PKfieldname})。
如果该字段已存在,请将下拉列表中选择的 ID 分配给该属性。

但是,edmx 生成中存在一个错误。

我大约一年前就注意到了这一点,而且它只在非常特殊的情况下才会发生。

当您通过 .edmx 设置关系时(右键单击 > 添加 > 关联...),您将看到一个窗口,要求您选择要关联的两个实体。

Random example image found online.

对于一对多关系,您必须确保 MANY 实体位于该窗口的右侧。(就像上图中一样)

向导完美地允许您执行相反的操作(基本上是设置多对一,如果您从左到右阅读)。如果您这样做,我提到的辅助 FK 字段将不会被设置。

当该字段未设置,并且您尝试通过 .PersonType 字段添加它时,EF 似乎经常尝试创建该对象。

要解决此问题,您必须删除关联,然后当 MANY 实体位于窗口右侧时再次添加它。

对于您的情况,这意味着 PersonType 应位于左侧,Person 应位于右侧。

完成后,让您的下拉列表填写 PersonType_Id 字段(如果您使用默认 PK,则应为 int)。将 PersonType 属性留空,并保存刚刚创建的 Person 对象。
然后,EF 应正确查找现有的 PersonType,而不是尝试创建新的。

您能否确认此解决方案是否适合您?

关于c# - 使用 MVC 5 和 Entity Framework 下拉关联实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28853881/

相关文章:

asp.net mvc 添加到 AUTHORIZE 属性

asp.net-mvc - IIS 压缩模块和 Vary : Accept-Encoding Header

c# - 如何使用 MVC3 中的 SAML 断言发布到另一个网站?

linq - EF : Is there way to force Linq using UNION instead of UNION ALL

c# - 未使用 LockScreen.SetImageFileAsync(file) 更新缓存图像;

c# - 二维整数数组到 DataGridView

c# - 在 WPF .NET Framework 中使用自定义任务管理器时,如何防止进程重复?

c# - Entity Framework : Invalid column name

c# - Composite Key EF Core 在使用 Fluent Api 时出错

c# - LINQ - 按多个属性对列表进行分组并返回带有数组成员的对象