【发布时间】:2019-01-08 08:43:39
【问题描述】:
自从我开始使用实体框架的 DATABASE FIRST 方法以来。它很容易上手,也很有趣,但有一件事让我感到困惑。
在 MVC 中,我们通常制作视图模型(具有正负属性的模型,因此它遵循特定的视图)。很好,但是在使用带有 DB 优先方法的 EF 时,这似乎是不可能的。因为我们从数据库表中创建了一个模型,然后继续使用它进行插入、更新、选择或任何操作。
例如
服务模式:
namespace ZahidCarWash.Models.EF
{
using System;
using System.Collections.Generic;
public partial class Services
{
public short ServiceID { get; set; }
public string ServiceName { get; set; }
public Nullable<decimal> ServicePrice { get; set; }
public Nullable<System.DateTime> EntryDateTime { get; set; }
public Nullable<bool> IsOwner { get; set; }
public Nullable<decimal> Commission { get; set; }
}
}
然后在控制器中使用它。
[HttpPost]
public JsonResult UpdateServices(Services UpdateServicesVM)
{
ServicesRepository ServicesRep = new ServicesRepository();
int i = 0;
//i = ServicesRep.UpdateServices(UpdateServicesVM, out ReturnStatus, out ReturnMessage);
ZahidCarWashDBEntities zjdb = new ZahidCarWashDBEntities();
zjdb.Entry(UpdateServicesVM).State = EntityState.Modified;
i= zjdb.SaveChanges();
return Json(new { ReturnMessageJSON = i > 0 ? "Success" : "Error", ReturnStatusJSON = i > 0 ? true : false });
}
或者
[HttpPost]
public JsonResult AddServices(Services AddServicesVM)
{
ServicesRepository ServicesRep = new ServicesRepository();
int i = 0;
//i = ServicesRep.InsertServices(AddServicesVM, out ReturnStatus, out ReturnMessage);
ZahidCarWashDBEntities context = new ZahidCarWashDBEntities();
context.Services.Add(AddServicesVM);
context.SaveChanges();
return Json(new { ReturnMessageJSON = ReturnMessage, ReturnStatusJSON = ReturnStatus });
}
我通过添加/删除属性创建了其他自定义模型,但这听起来不太好。有什么体面的方法或 EF 提供的吗?
【问题讨论】:
-
您应该为视图创建视图模型(而不是为/来自模型)。没有太多的工具,大多数程序员只是编写它们。代码生成工具(脚手架)仅支持直接 CRUD,这意味着您的数据模型定义了您的 UI。对于大多数好的网站来说都不好。
-
正确但假设一个视图正在传递一个视图模型A,但控制器正在处理模型B(由实体框架生成),所以参数应该是类型A,这就是问题
-
一个控制器可以使用 0 个或多个模型。它的工作是将查询转换为 ViewModel,并将结果转换为更新。
-
没听懂? ?
-
从 ViewModel A 更新/插入模型 B(也可能是模型 C)是 MVC 的正常工作流程。
标签: c# asp.net-mvc entity-framework entity-framework-6 asp.net-mvc-viewmodel