是否可以使用实体框架数据库优先方法从数据库表创建的模型之外创建视图模型? [英] Is it possible to create view models by out of models created from database tables using entity framework DB first approach?

查看:69
本文介绍了是否可以使用实体框架数据库优先方法从数据库表创建的模型之外创建视图模型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

自从我开始使用实体框架的DATABASE FIRST方法.容易抓住并有趣,但有一件事使我感到困惑.

Since I have started using DATABASE FIRST approach of entity framework. It's easy to catch on and interesting but there's one thing that puzzles me.

在MVC中,我们通常制作视图模型(具有正负属性的模型,因此它遵循特定的视图).很好,但是在将EF与数据库优先方法结合使用时,这似乎是不可能的.因为我们从数据库表创建一个模型,然后继续使用它进行插入,更新,选择或其他任何操作.

In MVC we usually make view models (models with plus-minus properties so it adheres to the particular view). Fine but while using the EF with DB first approach this seems to be impossible. Because we create one model off a database table and then keeps on using it for insert, update, select or anything.

例如

服务模型:

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

        }

        [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提供了任何体面的方式吗?

I created other customized models by adding/removing properties but that doesn't sound good. Any decent way to do or EF provides?

推荐答案

您在这里混合了两件事:数据库实体(实体数据模型)&查看模型是两个不同的概念.

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.

视图模型:从概念上讲,它与MV *体系结构模式有关,用于将数据传递到视图或从视图传递数据.使其与您的UI逻辑相关.

View Model: Conceptually, it is related to MV* architectural patterns and is used to pass data to/from a view. Keep it related to your UI logic.

要在使用Entity Framework的MVC应用程序中实现这两个概念,请将数据库表视为数据实体,并使其仅与数据库通信.要执行CRUD操作并在视图之间传递数据,请使用视图模型.

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. To perform CRUD operations and to pass data to and from a view, use View Models.

示例:

数据模型

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

查看模型

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

控制器

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

注意:在上面的代码中,我描述了在MVC应用程序中使用视图模型和数据实体的简单流程.在现实世界的项目中,人们会考虑使用诸如 Repository Pattern 之类的更多东西来执行CRUD操作,关注点分离原则(建议不要在操作方法中执行数据库操作控制器).为了映射不同的实体,我们可以使用 Automapper .还有许多其他因素需要检查,但是您可以对自己的疑问有所了解.

Note: In the code above, I have described the simple flow to work with View Models and Data Entities in an MVC application. 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). Also to map different entities, we can use Automapper. There are lot of other factors to be checked but you can get an idea about your doubt.

这篇关于是否可以使用实体框架数据库优先方法从数据库表创建的模型之外创建视图模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆