首页 > 解决方案 > Entity Framework 6 数据库优先 - 多对多:将其他模型中的项目添加到我的视图

问题描述

我有一个 Microsoft SQL Server 数据库,设计如下:一个 table Oeuvre,另一个 table Materiau,最后因为我处于多对多关系中,一个 table Oeuvre_Materiau

我正在使用 Visual Studio 2017,并按照可在此处找到的基本教程创建一个新项目:https ://docs.microsoft.com/en-us/aspnet/mvc/overview/getting-started/database-first -发展/

一切都很顺利,我的数据库设计也很顺利,我认为 Visual Studio 正确理解了我的数据库的设计方式,正如我们在这里看到的:

在此处输入图像描述

VS聪明,明白表Oeuvre_Materiau只是两个表之间的链接。

现在,可能是我出错了,但我正在生成控制器和视图,正如教程告诉我的那样,通过创建一个脚手架项目。

好的,我们有自己的看法,我可以创建和编辑内容,并且我的oeuvre表格按原样填充,一切都很好而且花花公子(不要担心另一个 xxx_ID,它们是一对一关系并按预期工作) :

在此处输入图像描述

现在,我正在尝试添加一个在我的表中materiau_name定义的下拉菜单。materiau

每个oeuvre项目可以有多个materiau_name,并且这些materiau-name元素在我materiau的 table 中定义,因此oeuvre_materiau中间的 table 仅包含 2 个元素,materiau_id并且oeuvre_id.

但我不知道如何做到这一点。我试图在我的视图中添加 table 中的元素materiau,但我找不到如何,并且我视图中调用的唯一模型是Oeuvre模型。

这是Oeuvre模型类:

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

    public partial class oeuvre
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public oeuvre()
        {
            this.materiau = new HashSet<materiau>();
        }

        public int oeuvre_id { get; set; }
        public Nullable<System.DateTime> created_on { get; set; }
        public Nullable<bool> is_deleted { get; set; }
        public string titre { get; set; }
        public Nullable<int> annee { get; set; }
        public string emplacement_signature { get; set; }
        public Nullable<int> longueur { get; set; }
        public Nullable<int> largeur { get; set; }
        public Nullable<int> hauteur { get; set; }
        public string historique { get; set; }
        public Nullable<int> categorie_id { get; set; }
        public Nullable<int> lieu_id { get; set; }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<materiau> materiau { get; set; }
    }
}

materiau模型类:

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

    public partial class materiau
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public materiau()
        {
            this.oeuvre = new HashSet<oeuvre>();
        }

        public int materiau_id { get; set; }
        public string materiau_name { get; set; }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<oeuvre> oeuvre { get; set; }
    }
}

oeuvresController: _

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using WebApplication8.Models;

namespace WebApplication8.Controllers
{
    public class oeuvresController : Controller
    {
        private CatalogueEntities db = new CatalogueEntities();

        // GET: oeuvres
        public ActionResult Index()
        {
            return View(db.oeuvre.ToList());
        }

        // GET: oeuvres/Details/5
        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }

            oeuvre oeuvre = db.oeuvre.Find(id);

            if (oeuvre == null)
            {
                return HttpNotFound();
            }
            return View(oeuvre);
        }

        // GET: oeuvres/Create
        public ActionResult Create()
        {
            return View();
        }

        // POST: oeuvres/Create
        // Afin de déjouer les attaques par sur-validation, activez les propriétés spécifiques que vous voulez lier. Pour 
        // plus de détails, voir  https://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "oeuvre_id,created_on,is_deleted,titre,annee,emplacement_signature,longueur,largeur,hauteur,historique,categorie_id,lieu_id")] oeuvre oeuvre)
        {
            if (ModelState.IsValid)
            {
                db.oeuvre.Add(oeuvre);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(oeuvre);
        }

        // GET: oeuvres/Edit/5
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }

            oeuvre oeuvre = db.oeuvre.Find(id);

            if (oeuvre == null)
            {
                return HttpNotFound();
            }

            return View(oeuvre);
        }

        // POST: oeuvres/Edit/5
        // Afin de déjouer les attaques par sur-validation, activez les propriétés spécifiques que vous voulez lier. Pour 
        // plus de détails, voir  https://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include = "oeuvre_id,created_on,is_deleted,titre,annee,emplacement_signature,longueur,largeur,hauteur,historique,categorie_id,lieu_id")] oeuvre oeuvre)
        {
            if (ModelState.IsValid)
            {
                db.Entry(oeuvre).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(oeuvre);
        }

        // GET: oeuvres/Delete/5
        public ActionResult Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }

            oeuvre oeuvre = db.oeuvre.Find(id);

            if (oeuvre == null)
            {
                return HttpNotFound();
            }

            return View(oeuvre);
        }

        // POST: oeuvres/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            oeuvre oeuvre = db.oeuvre.Find(id);
            db.oeuvre.Remove(oeuvre);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}

Index观点:

@model IEnumerable<WebApplication8.Models.oeuvre>

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.created_on)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.is_deleted)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.titre)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.annee)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.emplacement_signature)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.longueur)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.largeur)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.hauteur)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.historique)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.categorie_id)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.lieu_id)
        </th>
        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.created_on)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.is_deleted)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.titre)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.annee)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.emplacement_signature)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.longueur)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.largeur)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.hauteur)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.historique)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.categorie_id)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.lieu_id)
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id=item.oeuvre_id }) |
            @Html.ActionLink("Details", "Details", new { id=item.oeuvre_id }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.oeuvre_id })
        </td>
    </tr>
}

</table>

创建视图:

@model WebApplication8.Models.oeuvre

@{
    ViewBag.Title = "Create";
}

<h2>Create</h2>


@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>oeuvre</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })


        <div class="form-group">
            @Html.LabelFor(model => model.titre, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.titre, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.titre, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.annee, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.annee, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.annee, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.emplacement_signature, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.emplacement_signature, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.emplacement_signature, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.longueur, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.longueur, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.longueur, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.largeur, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.largeur, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.largeur, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.hauteur, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.hauteur, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.hauteur, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.historique, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.historique, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.historique, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.categorie_id, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.categorie_id, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.categorie_id, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.lieu_id, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.lieu_id, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.lieu_id, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

EDIT 和 DETAIL 视图非常相似。

所以,我只是想在我的不同视图中添加一个下拉框,它将被填充并填充链接表 oeuvre_materiau:

在此处输入图像描述

标签: c#sql-serverasp.net-mvcentity-framework-6

解决方案


推荐阅读