实体框架与MVC模型

发布于 2024-11-30 07:34:44 字数 3398 浏览 0 评论 0 原文

我们的团队目前正在开发一个 Web 应用程序,我们有一个添加了实体框架 .edmx 的类库,并生成了 POCO 类。

我们的 Web 应用程序基于 MVC,我们在具有相同名称和属性的模型中定义了我们的类(从 .edmx 复制粘贴 POCO 类)。 .edmx 类库被引用到 MVC Web 应用程序。

视图是强类型的 MVC 模型类。我们使用 MVC 模型来显示、StringLength 和 StringLength。必需的。

在我们的控制器中,当存在 CRUD 操作时,我们接受 POCO 类类型,例如

     public ActionResult Create(EFModels.User user)    {    }

EFModels.User 是来自 .edmx(POCO 生成的类)的类,并且 MVC 视图强类型化为 MvcWebApplication.Models.User 模型。

问题是我们如何在 ActionResult Create 中从 MvcWebApplication.Models.User (来自模型)获取数据到 EFModels.User (EF 类)?

我能够获取数据,我知道它具有相同的属性名称。我尝试更改类名称,但它仍然有效,但如果我们更改属性名称,它就不起作用。我无法理解其背后的逻辑。

最初我们不知道它不起作用,我们使用 AutoMapper 将模型类转换为 Edmx POCO 类。

任何想法,谢谢。

问题是我们如何通过任何映射将模型类的值获取到 EF 类。我不需要使用 AutoMapper,不使用它我就能获取值。

看一下代码,希望能解释得更好...

//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 模型类

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

<%@ 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");
    }

当我点击 Create 按钮时,我正在发布 MvcWebSamp.Models 类型的数据。 User 并在 Create Action 中,我无需使用任何 AutoMapper 即可获取 EFModels.User 用户类型的数据。我想知道这是如何工作的???

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.

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). The .edmx class library is refrenced to MVC web application.

The Views are strongly typed of MVC Model classes. We have used MVC Models for Display, StringLength & Required.

In our controller when there is a CRUD operation we are accepting the POCO Classes Type such as

     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.

Question is how are we getting data from the MvcWebApplication.Models.User (from Model) to EFModels.User (EF class) in the ActionResult Create ??

I am able to get the data, I know it is coz of the same property name. 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.

Any ideas, Thanks.

The question is how are we getting the values of the Model Class to the EF class with any mapping. I don`t need to use AutoMapper, without using that I am getting the values.

Have a look at the code, hope that explains better...

//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

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

<%@ 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. I want to know how this works???

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

梦巷 2024-12-07 07:34:44

您应该使用视图模型作为创建方法的参数类型:

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

    return View(model);
}

控制器应该设计为创建和接受视图模型,并将这些视图模型传递给与数据层交互的适当服务以创建域模型。这使得你的控制器动作变得相当薄。

您可以在服务中使用 AutoMapper 之类的东西来轻松映射视图模型和域模型:

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

You should be using your view model as the argument type for your create method:

[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:

var user = Mapper.Map<UserViewModel, User>(model);
看透却不说透 2024-12-07 07:34:44

通过将 DbContext 提供给 UI 层,您可以在 UI 和数据库之间创建依赖关系。尝试将其分离并使用存储库模式和依赖项注入。

参考:
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

By giving DbContext to UI Layer you are creating dependancy between UI and database. 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://prodinner.codeplex.com/releases/view/66899
眼波传意 2024-12-07 07:34:44

您根本没有使用 MvcWebSamp - 正如您所看到的,控制器采用 EFModel

public ActionResult Create(EFModels.User user)

它可以工作,因为属性是相同的。您只需修改控制器方法签名以采用 MvcWebSamp 对象,然后将这些对象转换为 EFModel 对象。

You aren't using your MvcWebSamp at all - as you can see, the controller takes the 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.

倾城°AllureLove 2024-12-07 07:34:44

自动映射器应该可以工作。即使属性名称不同,我们也一直使用它。请发布不适合您的自动映射器的使用情况。否则,请参阅以下帖子以使其适用于不同的属性名称。

属性名称不同时 Automapper 的使用

Automapper should work. We use it all the time even with different property names. Please post usage of automapper that does not work for you. Otherwise see following post to make it work with different property names.

Usage of Automapper when property names are different

誰認得朕 2024-12-07 07:34:44

为了使用实体框架,您需要创建实体数据模型。要添加实体模型:

1) 右键单击​​解决方案资源管理器中的模型文件夹。
2) 选择添加新项目。

有关更多详细信息,请查看以下链接...

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

谢谢!!!

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.
2) Select Add a New Item.

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

Thanks !!!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文