使用 LINQ to SQL class C# MVC 联合视图的 CRUD

CRUD for joinned view with LINQ to SQL class C# MVC

这是我的问题的一些背景知识:

  1. 我的应用程序中有一个强类型视图,用于显示列表。
  2. 一旦我要显示的信息来自不同的表,我就必须在我的 LINQ 查询中进行一些连接,因此我必须创建一个自定义模型。
  3. 现在我想使用我的列表行的ID来实现CRUD操作。

模特

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
using System.Globalization;
using System.Web.Security;

namespace LMWEB_MVC.Models
{
    public class LeaseViewModel
    {
        [Key] public int Lease_Detail_ID { get; set; }
        public string Lease_ID { get; set; }
        public string XRef_Lease_ID { get; set; }
        public string Vendor_Name { get; set; }
        public string Description { get; set; }
        public string County { get; set; }
        public decimal Amount { get; set; }
        public DateTime Payment_Due_Date { get; set; }
        public short Authorized { get; set; }
        public string Line_Type { get; set; }
    }

    public class LeasesContext : DbContext
    {
        public LeasesContext()
            : base("LMWEBConnectionString1")
        {
            Database.SetInitializer<Models.LeasesContext>(null);
        }

        public DbSet<LeaseViewModel> LeaseViewModels { get; set; }
    }

}

风景

@model IEnumerable<LMWEB_MVC.Models.LeaseViewModel>

@{
    ViewBag.Title = "Leases";
}

<link href="../Styles/style.css" rel="stylesheet" type="text/css">

<h2>Leases</h2>
<div>

</div>
<div>
    <p>
        @Html.ActionLink("Create New", "Create")
    </p>
</div>
<div style="scrollbar-base-color: #eeeeee; background: white; position: relative; border-right: black 1px solid;
border-top: black 1px solid; overflow-y: scroll; border-left: black 1px solid; border-bottom: black 1px solid;
height: 650px; width:100%; border-spacing: 10px 10px">
    <table>
        <tr>
            <th style="width: 65px;" class="head">
                @Html.DisplayNameFor(model => model.Lease_ID)
            </th>
            <th style="width: 75px;" class="head">
                @Html.DisplayNameFor(model => model.XRef_Lease_ID)
            </th>
            <th style="width: 85px;" class="head">
                @Html.DisplayNameFor(model => model.Vendor_Name)
            </th>
            <th style="width: 185px;" class="head">
                @Html.DisplayNameFor(model => model.Description)
            </th>
            <th style="width: 85px;" class="head">
                @Html.DisplayNameFor(model => model.County)
            </th>
            <th style="width: 85px;" class="head">
                @Html.DisplayNameFor(model => model.Amount)
            </th>
            <th style="width: 60px;" class="head">
                @Html.DisplayNameFor(model => model.Payment_Due_Date)
            </th>
            @*<th style="width: 70px;" class="head">
                    @Html.DisplayNameFor(model => model.Authorized)
                </th>*@
            <th style="width: 70px;" class="head">
                @Html.DisplayNameFor(model => model.Line_Type)
            </th>
            <th style="width: 20px;" class="head"></th>
        </tr>

        @foreach (var item in Model)
        {
            <tr>
                <td style="width: 65px; word-wrap: break-word;" class="leasegrid">
                    @Html.DisplayFor(modelItem => item.Lease_ID)
                </td>
                <td style="width: 75px; word-wrap: break-word;" class="leasegrid">
                    @Html.DisplayFor(modelItem => item.XRef_Lease_ID)
                </td>
                <td style="width: 85px; word-wrap: break-word;" class="leasegrid">
                    @Html.DisplayFor(modelItem => item.Vendor_Name)
                </td>
                <td style="width: 185px; word-wrap: break-word;" class="leasegrid">
                    @Html.DisplayFor(modelItem => item.Description)
                </td>
                <td style="width: 85px; word-wrap: break-word;" class="leasegrid">
                    @Html.DisplayFor(modelItem => item.County)
                </td>
                <td style="width: 85px; word-wrap: break-word;" class="leasegrid">
                    @Html.DisplayFor(modelItem => item.Amount)
                </td>
                <td style="width: 60px; word-wrap: break-word;" class="leasegrid">
                    @Html.DisplayFor(modelItem => item.Payment_Due_Date)
                </td>
                @*<td class="leasegrid">
                           @Html.DisplayFor(modelItem => item.Authorized)
                    </td>*@
                <td style="width: 70px;" class="leasegrid">
                    @Html.DisplayFor(modelItem => item.Line_Type)
                </td>
                <td style="width: 140px;" class="leasegrid">
                    @Html.ActionLink("Edit", "Edit", new { item.Lease_Detail_ID }, null) |
                    @Html.ActionLink("Details", "Details", new { item.Lease_Detail_ID }, null) |
                    @Html.ActionLink("Delete", "Delete", new { item.Lease_Detail_ID }, null)
                </td>
            </tr>
        }

    </table>
</div>

控制器

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

namespace LMWEB_MVC.Controllers
{
    public class LeasesController : Controller
    {

        public ActionResult Leases()
        {
            LMWEBLINQDataContext leases = new LMWEBLINQDataContext();
            var leaseList = (from l in leases.tblfLeaseDetails
                             join v in leases.tblvVendors on l.Vendor_ID equals v.Vendor_ID
                             join c in leases.tblvCounties on l.County_ID equals c.County_ID
                             join a in leases.tblfAuthorizations on l.Lease_Detail_ID equals a.Lease_Detail_ID
                             join t in leases.tblvLineTypes on l.Line_Type_ID equals t.Line_Type_ID
                             select new
                             {
                                 l.Lease_Detail_ID,
                                 l.Lease_ID,
                                 l.XRef_Lease_ID,
                                 v.Vendor_Name,
                                 l.Description,
                                 c.County,
                                 l.Amount,
                                 l.Payment_Due_Date,
                                 a.Authorized,
                                 t.Line_Type
                             }).Distinct().ToList().ToNonAnonymousList(new List<LeaseViewModel>()).Take(10);

            ViewBag.Message = "Your app description page.";
            return View(leaseList);
        }

        private LeasesContext db = new LeasesContext();

        //
        // GET: /Leases/

        public ActionResult Index()
        {
            return View(db.LeaseViewModels.ToList());
        }

        //
        // GET: /Leases/Details/5

        public ActionResult Details(int Lease_Detail_ID = 0)
        {
            LeaseViewModel leaseviewmodel = db.LeaseViewModels.Find(Lease_Detail_ID);
            if (leaseviewmodel == null)
            {
                return HttpNotFound();
            }
            return View(leaseviewmodel);
        }

        //
        // GET: /Leases/Create

        public ActionResult Create()
        {
            return View();
        }

        //
        // POST: /Leases/Create

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(LeaseViewModel leaseviewmodel)
        {
            if (ModelState.IsValid)
            {
                db.LeaseViewModels.Add(leaseviewmodel);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(leaseviewmodel);
        }

        //
        // GET: /Leases/Edit/5

        public ActionResult Edit(int Lease_Detail_ID = 0)
        {
            LeaseViewModel leaseviewmodel = db.LeaseViewModels.Find(Lease_Detail_ID);
            if (leaseviewmodel == null)
            {
                return HttpNotFound();
            }
            return View(leaseviewmodel);
        }

        //
        // POST: /Leases/Edit/5

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(LeaseViewModel leaseviewmodel)
        {
            if (ModelState.IsValid)
            {
                db.Entry(leaseviewmodel).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(leaseviewmodel);
        }

        //
        // GET: /Leases/Delete/5

        public ActionResult Delete(int Lease_Detail_ID = 0)
        {
            LeaseViewModel leaseviewmodel = db.LeaseViewModels.Find(Lease_Detail_ID);
            if (leaseviewmodel == null)
            {
                return HttpNotFound();
            }
            return View(leaseviewmodel);
        }

        //
        // POST: /Leases/Delete/5

        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int Lease_Detail_ID)
        {
            LeaseViewModel leaseviewmodel = db.LeaseViewModels.Find(Lease_Detail_ID);
            db.LeaseViewModels.Remove(leaseviewmodel);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

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

我收到的错误

'System.Data.EntityCommandExecutionException' 类型的异常发生在 System.Data.Entity.dll 但未在用户代码中处理

附加信息:执行命令定义时出错。有关详细信息,请参阅内部异常。

内部异常

{"Invalid object name 'dbo.LeaseViewModels'."}

最后 (感谢您达到这一点) 我的问题:

我知道 none 我的 CRUD 操作正在完成,因为我的数据库中没有 dbo.LeaseViewModels。 LeaseViewModels 只是我创建的一个模型,用于存储我的连接查询。所以这是我的疑问:如何从这个自定义视图开始在我的数据库中实现 CRUD 操作?可能吗?如果不是,如果没有自定义模型,我如何创建一个包含来自不同表的信息的视图?

注意:我没有 DBO 访问我的数据库的权限。我只能读取和执行程序。

您创建 DbContext class 的方式是寻找一个名为 LeaseViewModel 的 table。如果您无法创建 table,您需要更改 DbContext 以实际将 DbSets 保存到 tblfLeaseDetails、tblvVendors、tblvCounties 等。然后在控制器中(或者更好的是在某些 DAL 模块中),您可以使用连接与您的创建视图模型类似,然后在控制器中使用该视图模型。

问题出在您的 DbContext 中。 DbContext class 应该将数据库表映射到应用程序的域 classes。

从 DbContext 中删除 LeaseViewModel 并添加数据库的表(例如 Vendor 和 Country)。然后,您可以使用 linq 表达式连接表,并 return 视图的 LeaseViewModel 对象。

希望对您有所帮助。

更新

我正在添加一些关于 EF 映射的链接,它们可能会对您有所帮助: