简体   繁体   English

实体框架和MVC模型

[英]Entity Framework & MVC Models

Our team is currently developing a web application, in that we have a class library with Entity Framework .edmx added and have generated the POCO classes. 我们的团队目前正在开发一个Web应用程序,因为我们添加了一个包含Entity Framework .edmx的类库,并生成了POCO类。

Our Web Application is based on MVC, we have defined our classes in models with the same name and attributes (copy paste of the POCO classes from the .edmx). 我们的Web应用程序基于MVC,我们在具有相同名称和属性的模型中定义了我们的类(从.edmx复制粘贴POCO类)。 The .edmx class library is refrenced to MVC web application. .edmx类库被引用到MVC Web应用程序。

The Views are strongly typed of MVC Model classes . 视图是MVC模型类的强类型。 We have used MVC Models for Display, StringLength & Required. 我们使用了MVC模型用于Display,StringLength和Required。

In our controller when there is a CRUD operation we are accepting the POCO Classes Type such as 在我们的控制器中,当存在CRUD操作时,我们接受POCO类类型,例如

     public ActionResult Create(EFModels.User user)    {    }

EFModels.User is a class from the .edmx (POCO generated class) and the MVC View is strongly typed to the model which is MvcWebApplication.Models.User. EFModels.User是来自.edmx(POCO生成的类)的类,MVC视图是强类型的模型,即MvcWebApplication.Models.User。

Question is how are we getting data from the MvcWebApplication.Models.User (from Model) to EFModels.User (EF class) in the ActionResult Create ?? 问题是我们如何从ActionResult Create中的MvcWebApplication.Models.User(从Model)获取数据到EFModels.User(EF类)?

I am able to get the data, I know it is coz of the same property name. 我能够获取数据,我知道它是同一属性名称的coz。 I tried changing the class name but still it works, but if we change the property name it does not work. 我尝试更改类名但仍然有效,但是如果我们更改属性名称则不起作用。 I cannot understand the logic behind it. 我无法理解它背后的逻辑。

Initially we never knew it didn`t work and we were using AutoMapper to convert the Model Class to Edmx POCO class. 最初我们从来不知道它没有用,我们使用AutoMapper将Model Class转换为Edmx POCO类。

Any ideas, Thanks. 任何想法,谢谢。

The question is how are we getting the values of the Model Class to the EF class with any mapping. 问题是我们如何使用任何映射将Model Class的值获取到EF类。 I don`t need to use AutoMapper, without using that I am getting the values. 我不需要使用AutoMapper,而不使用我得到的值。

Have a look at the code, hope that explains better... 看看代码,希望更好地解释......

//POCO CLASS // POCO CLASS

namespace EFModels
{
    using System;
    using System.Collections.Generic;

    public partial class User
    {
        public int Id { get; set; }
        public string Type { get; set; }
        public string Name { get; set; }
    }
}

//MVC Model Class // MVC模型类

namespace MvcWebSamp.Models
{
    public class User
    {
        public int Id { get; set; }

        [Display(ResourceType = typeof(BasicTags), Name = "Type")]
        [StringLength(15, ErrorMessageResourceName = "TypeLength", ErrorMessageResourceType = typeof(BasicTags))]
        [Required(ErrorMessageResourceName = "TypeRequired", ErrorMessageResourceType = typeof(BasicTags))]
        public string TypeName { get; set; }
        public string Name { get; set; }

        public Address Address { get; set; }
    }
}

//MVC VIEW PAGE // MVC VIEW PAGE

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<MvcWebSamp.Models.User>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    User
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

<h2>User</h2>
  <% using (Html.BeginForm("Create", "User", FormMethod.Post))
       { 
    %>
     <%: Html.ValidationSummary(true) %>
    <fieldset>
        <legend>User</legend>
        <div class="editor-field">
            <%: Html.LabelFor(model => model.TypeName) %>
            <%: Html.EditorFor(model => model.TypeName)%>
            <%: Html.ValidationMessageFor(model => model.TypeName)%>
        </div>
        <div class="editor-field">
            <%: Html.LabelFor(model => model.Name) %>
            <%: Html.EditorFor(model => model.Name)%>
             <%: Html.EditorFor(model => model.Address.street)%>
        </div>

        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
    <% } %>
</asp:Content>

//Controller Method //控制器方法

 public ActionResult Create(EFModels.User user)
    {
        Model1Container con = new Model1Container();
        con.Users.Add(user);
        con.SaveChanges();
        return View("User");
    }

When I hit the Create Button, I am posting data of the type MvcWebSamp.Models.User and in the Create Action I am able to get the data of the type EFModels.User user without using any AutoMapper. 当我点击“创建”按钮时,我发布了MvcWebSamp.Models.User类型的数据,并且在“创建操作”中,我可以在不使用任何AutoMapper的情况下获取EFModels.User类型的数据。 I want to know how this works??? 我想知道这是如何工作的???

You should be using your view model as the argument type for your create method: 您应该使用视图模型作为create方法的参数类型:

[HttpPost]
public ActionResult Create(UserViewModel model)
{
    if (ModelState.IsValid)
    {
        int id = UserService.CreateFromViewModel(model);
        return RedirectToAction("View", new { id });
    }

    return View(model);
}

You controller should be designed to create and accept view models, and it passes those to an appropriate service which interacts with your data layer to create your domain model. 您应该将控制器设计为创建和接受视图模型,并将其传递给与您的数据层交互的适当服务,以创建您的域模型。 This keeps your controller action quite thin. 这可以使您的控制器动作非常薄。

You can use something like AutoMapper in your service to easily map between your view model and your domain model: 您可以在服务中使用类似AutoMapper的内容 ,轻松地在您的视图模型和域模型之间进行映射:

var user = Mapper.Map<UserViewModel, User>(model);

By giving DbContext to UI Layer you are creating dependancy between UI and database. 通过将DbContext提供给UI层,您可以在UI和数据库之间创建依赖关系。 Try to seperate it and use repository pattern and dependency injection. 尝试分离它并使用存储库模式和依赖注入。

Reference: http://blogs.msdn.com/b/adonet/archive/2009/06/16/using-repository-and-unit-of-work-patterns-with-entity-framework-4-0.aspx 参考: http//blogs.msdn.com/b/adonet/archive/2009/06/16/using-repository-and-unit-of-work-patterns-with-entity-framework-4-0.aspx

http://prodinner.codeplex.com/releases/view/66899

Automapper should work. Automapper应该工作。 We use it all the time even with different property names. 即使使用不同的属性名称,我们也会一直使用它。 Please post usage of automapper that does not work for you. 请发布不适合您的automapper用法。 Otherwise see following post to make it work with different property names. 否则请参阅以下帖子,使其适用于不同的属性名称。

Usage of Automapper when property names are different 当属性名称不同时使用Automapper

You aren't using your MvcWebSamp at all - as you can see, the controller takes the EFModel 您根本没有使用MvcWebSamp - 正如您所看到的,控制器采用EFModel

public ActionResult Create(EFModels.User user)

It works because the properties are the same. 它的作用是因为属性是相同的。 You just need to modify the controller method signatures to take the MvcWebSamp objects instead, and then transform those objects to the EFModel objects. 您只需修改控制器方法签名即可获取MvcWebSamp对象,然后将这些对象转换为EFModel对象。

In order to use the Entity Framework, you need to create an Entity Data Model. 要使用实体框架,您需要创建实体数据模型。 For adding Entity Model: 用于添加实体模型:

1) Right click on Model Folder in the solution explorer. 1)右键单击解决方案资源管理器中的模型文件夹。 2) Select Add a New Item. 2)选择添加新项。

for more details please check out the following link.... 有关详细信息,请查看以下链接....

http://www.mindstick.com/Articles/6f3bb3c6-d195-487b-8b82-244bb417b249/?Model%20classes%20with%20Entity%20Framework%20in%20MVC http://www.mindstick.com/Articles/6f3bb3c6-d195-487b-8b82-244bb417b249/?Model%20classes%20with%20Entity%20Framework%20in%20MVC

Thanks !!! 谢谢 !!!

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM