简体   繁体   English

是否可以使用实体框架数据库优先方法从数据库表创建的模型之外创建视图模型?

[英]Is it possible to create view models by out of models created from database tables using entity framework DB first approach?

Since I have started using DATABASE FIRST approach of entity framework. 自从我开始使用实体框架的DATABASE FIRST方法。 It's easy to catch on and interesting but there's one thing that puzzles me. 容易上手,有趣,但有一件事使我感到困惑。

In MVC we usually make view models (models with plus-minus properties so it adheres to the particular view). 在MVC中,我们通常会创建视图模型(具有正负属性的模型,因此它会遵循特定的视图)。 Fine but while using the EF with DB first approach this seems to be impossible. 很好,但是在将EF与数据库优先方法结合使用时,这似乎是不可能的。 Because we create one model off a database table and then keeps on using it for insert, update, select or anything. 因为我们从数据库表创建一个模型,然后继续使用它进行插入,更新,选择或其他任何操作。

eg 例如

Services model: 服务模式:

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; }
    }
}

and then using it in controllers. 然后在控制器中使用它。

        [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 });

        }

Or 要么

        [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 });

        }

I created other customized models by adding/removing properties but that doesn't sound good. 我通过添加/删除属性创建了其他自定义模型,但这听起来不太好。 Any decent way to do or EF provides? EF提供了任何体面的方式吗?

You are mixing two things here: Database Entities (Entity Data Model) & View Models which are two different concepts. 您在这里混合了两件事:数据库实体(实体数据模型)和视图模型,这是两个不同的概念。

  • Data Model: It is a simple class related to specified table from the database and can be used in the code as data model. 数据模型:这是与数据库中的指定表相关的简单类,可以在代码中用作数据模型。

  • View Model: Conceptually, it is related to MV* architectural patterns and is used to pass data to/from a view. 视图模型:从概念上讲,它与MV *体系结构模式有关,用于将数据传递到视图或从视图传递数据。 Keep it related to your UI logic. 使其与您的UI逻辑相关。

To implement these two concepts in an MVC application using Entity Framework, consider the database tables as Data Entities and keep it only to communicate with database. 要在使用Entity Framework的MVC应用程序中实现这两个概念,请将数据库表视为数据实体,并使其仅与数据库通信。 To perform CRUD operations and to pass data to and from a view, use View Models. 要执行CRUD操作并在视图之间传递数据,请使用视图模型。

Example: 例:

Data Model 资料模型

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; }
    }
}

View Model 查看模型

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

    public class ServiceViewModel
    {
        public short ServiceID { get; set; }
        public string ServiceName { get; set; }
        public decimal ServicePrice { get; set; }
        public System.DateTime EntryDateTime { get; set; }
        public bool IsOwner { get; set; }
        public decimal Commission { get; set; }
    }
}

Controller 控制者

[HttpPost]
public JsonResult AddServices(ServiceViewModel model)
{
    if(model == null)
       return null;

    var addService = new Services(); 
    //Use Automapper for mapping view models to data entities
    addService.ServiceID = model.ServiceID ;  //Service Id should be auto incremented from database
    addService.ServiceName = model.ServiceName ;
    addService.ServicePrice = model.ServicePrice ;
    addService.EntryDateTime = model.EntryDateTime ;
    addService.IsOwner = model.IsOwner ;
    addService.Commission = model.Commission ;


    ServicesRepository servicesRep = new ServicesRepository();
    int i = 0;
    //i = ServicesRep.UpdateServices(UpdateServicesVM, out ReturnStatus, out ReturnMessage);

    //Don't write the data specific logic in controllers. Use Repository Pattern.
    ZahidCarWashDBEntities context = new ZahidCarWashDBEntities();
    context.Services.Add(addService);
    context.SaveChanges();
    return Json(new { ReturnMessageJSON = ReturnMessage, ReturnStatusJSON = ReturnStatus });  

Note: In the code above, I have described the simple flow to work with View Models and Data Entities in an MVC application. 注意:在上面的代码中,我描述了在MVC应用程序中使用视图模型和数据实体的简单流程。 In real world projects, people consider lot more things like Repository Pattern to perform CRUD operation, Separation of Concerns principle (it is not advisable to perform database operations in action methods of a controller). 在现实世界的项目中,人们考虑使用诸如“ 存储库模式”之类的更多东西来执行CRUD操作, “关注分离”原理(不建议在控制器的操作方法中执行数据库操作)。 Also to map different entities, we can use Automapper . 为了映射不同的实体,我们可以使用Automapper There are lot of other factors to be checked but you can get an idea about your doubt. 还有许多其他因素需要检查,但是您可以对自己的疑问有所了解。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用Entity Framework 7在代码中首先处理这两个模型? - How handle these two models in code first approach using Entity Framework 7? 是否可以将数据库优先模型和代码优先模型与实体框架混合使用? - Is it possible to mix database first and code first models with entity framework? 实体框架代码首先在数据库中重命名模型/表 - Entity Framework Code first rename models/tables in Database 如何仅获取特定表以使用 C# 中的 Entity Framework Core 从数据库创建模型 - How to get only specific tables to create models from database with Entity Framework Core in C# 在Entity Framework中先从数据库更新元数据模型不起作用 - Metadata updating models from database first in Entity Framework does not work 实体框架数据库优先从基类继承模型 - Entity Framework Database First inherits models from base class 实体框架代码第一个数据库未与模型同步 - Entity Framework code first database not synced with models 在ASP.net MVC中使用Entity Framework创建模型时,如何在单个视图中从两个表中调用数据 - How to call data from two tables in a single View when created models with Entity Framework in ASP.net MVC 如何使用实体框架代码优先方法正确创建数据库 - How to correctly create a database using entity framework code first approach 在Entity Framework 6.0中从数据库更新模型 - Updating models from database in Entity Framework 6.0
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM