ASP.NET MVC 4项目没有任何ORM [英] ASP.NET MVC 4 project without any ORM

查看:142
本文介绍了ASP.NET MVC 4项目没有任何ORM的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用ASP.NET MVC没有EF和可能不LINQ。首先,我创建只是一个表/模型/控制器/视图在VS2010基本ASP.net MVC模板(索引页和索引的方法来实现)。我目前使用的try /错误会为网络上的所有教程都是基于EF和我有一个嵌入式C的背景。

我的问题是:

  • 是结构是否正确?

  • 我看到了存储库模式是用在一些开源项目,如nearforums。什么是它的优势,它是如何适应这一点,它取代DAL?

  • 我应该通过数据表来查看或物体重新presenting的数据表?

  • 我可以通过多个模型剃须刀页?如何列出2个不同的表的例子吗?

  • 是更好地把所有DAL code在一个文件?

DAL:

 使用系统;
使用System.Collections.Generic;
使用System.Linq的;
使用的System.Web;
使用System.Data这;
使用System.Configuration;
使用MySql.Data.MySqlClient;

命名空间MvcApplication1.Models
{
  公共类DAL
  {
    公共DAL()
    {}
    公开数据表getDataTable(字符串tableName值)
    {
      使用(康涅狄格州的MySqlConnection =新的MySqlConnection(ConfigurationManager.ConnectionStrings [MySQLConn。的ConnectionString))
      {
        使用(的MySqlCommand命令= conn.CreateCommand())
        {
          command.CommandText =选择*+ tablename;如果
          command.CommandType = CommandType.Text;

          conn.Open();

          无功表=新的DataTable();
          table.Load(Command.ExecuteReader却());

          返回表;
        }
      }
    }
  }
}
 

的重新presents产品表中code Product.cs类:

 命名空间MvcApplication1.Models
{
  公共类产品
  {
      公众诠释的ProductId {获得;组; }
      公共字符串名称{;组; }
      公共字符串生产者{获得;组; }
      公众诠释单价{获得;组; }
  }
}
 

ProductController.cs

 命名空间MvcApplication1.Controllers
{
    公共类ProductController的:控制器
    {
        //
        // GET:/产品/
      DAL DAL =新DAL();
        公众的ActionResult指数()
        {
          数据表DT = dal.getDataTable(产品);
          产品[]产品=新产品[dt.Rows.Count]
          的for(int i = 0; I< dt.Rows.Count;我++)
          {
            产品[I] =新产品();
            产品[I] .ProductId =(int)的dt.Rows [I] [的ProductId];
            产品[I] .Name点=(字符串)dt.Rows [I] [名称];
            产品[I] .Producer =(字符串)dt.Rows [I] [制作人];
            产品[I] .UnitPrice = Decimal.ToInt32((十进制)dt.Rows [I] [单价]);
          }

          返回查看(产品);
        }
........
........
}
 

Index.cshtml:

  @model IEnumerable的< MvcApplication1.Models.Product>
@ {
    ViewBag.Title =指数;
}

< H2>指数< / H>
@foreach(以模型的VaR项)
{
    &其中; TR>
        < TD>
            @ Html.DisplayFor(modelItem => item.ProductId)
        < / TD>
        < TD>
            @ Html.DisplayFor(modelItem => item.Name)
        < / TD>
        < TD>
            @ Html.DisplayFor(modelItem => item.Producer)
        < / TD>
        < TD>
            @ Html.DisplayFor(modelItem => item.UnitPrice)
        < / TD>
        < TD>
            @ Html.ActionLink(编辑,编辑,新{ID = item.ProductId})|
            @ Html.ActionLink(细则,细则,新{ID = item.ProductId})|
            @ Html.ActionLink(删除,删除,新{ID = item.ProductId})
        < / TD>
        < BR>
    < / TR>
}
 

解决方案

我看到了存储库模式是用在一些开源项目,如nearforums。什么是它的优势,它是如何适应这一点,它取代DAL?

的存储库模式的好处是,它可以让你切换你的数据访问逻辑/ ORM。例如,如果你想从实体框架转换到NHibernate的,你只要更新注册你内心的IoC容器和像变魔术一样的code为使用NHibernate 0知识,你曾经做出的开关。它可以让你的code是不可知底层的持久性框架。对于所有它知道,结果code从文件,Web服务调用,或在内存中的列表来了。您还可以得到重用,你不得不做出从其他组件相同的查询事件。另一种增益单元测试。根据您目前的实现,你不能单元测试控制器,这将直接每次都连接到数据库,从而定义使其成为集成测试。你一定会希望利用一个ORM,否则你会写同一code一遍又一遍,直到它让你哭泣。建立/拆除连接,类型转换,所有的原语原生的.NET类型等方面与本地ADO.NET,亦是过去的事情了现在。使您的生活更轻松,并使用ORM。与此同时,随着大国意味着巨大的责任。奥姆斯可以是一个噩梦,如果你不验证正在生成和对数据库执行的查询。如果使用不当,他们会产生性能问题。您将能够利用LINQ对大多数的查询,但有时你必须弄脏质朴天然的和去与原始的SQL。你ORM将仍然能够处理这两种方案。

如果我通过数据表来查看或物体重新presenting的数据表?

您肯定不希望传递数据表。你想通过视图模型或实体视图。该视图应该一无所知数据库。你要做的就是给它的数据,并显示在屏幕上永远不知道数据的来源。你要小心,如果你正在使用像NHibernate的直接传递实体到你的观点,因为您在使用延迟加载和N + 1查询相关的问题。查看模型通常精简下来的实体的版本。例如,如果你有4个属性,但只需要消耗这些属性的2/4认为一个实体,你会做有2个属性一个独立的视图模型,并使用映射库像Automapper从你的实体地图来查看模型。

我可以通过多个模型剃须刀页?如何列出2个不同的表,例如?

这是很简单的。你让一个顶级对象,并给它2个属性重新present您要访问的实体。

 公共类MyViewModel
{
  公共类使用实体FirstObject {获得;组; }

  公共类实体2 SecondObject {获得;组; }
}
 

然后,你会成为一个强类型的视图,并使用你张贴在你的问题你的剃须刀视图中使用的强类型的视图助手渲染FirstObject和SecondObject。 @ Html.TextBoxFor()等。

最后,您的控制器将接受MyViewModel作为参数,并填充FirstObject和SecondObject根据您的观点呈现的表单输入。

是更好地把所有DAL code在一个文件?

您想要把相关DAL code在同一个文件。事情通常是制定了由表,但是这一切都取决于(什么是你的聚合根为例)你的对象之间的关系。你不希望做的是盲目实施每桌一个存储库。你刚刚结束了一个真正的程序和贫血的数据模型,导致拼接在一起,通过多次调用数据库对象图和关系。我建议你​​寻找到领域驱动设计,以获取有关如何解决这个问题的一个好办法。

我只是皮毛这里。你基本上需要搭载了最新的模式和做法,如果你想要做的这个东西正常。这是一个不同的运动都在一起。不喜欢隐藏文件单片code,视图状态,和DataGrid控件的美好时光。有一些很好的书在那里,如:

布朗菲尔德应用开发 领域驱动设计(埃里克·埃文斯) 清洁codeR(罗伯特·Ç·马丁) 重构:提高现有code设计(马丁·福勒) 企业应用架构模式(马丁·福勒)

我并不是说读这些书一字不差,但我强烈推荐第2。我敢肯定,社会将有更多的要说一下这些发展的做法,但是这是我上的所有观点。谢谢,祝你好运。

I am trying to use ASP.NET MVC without EF and possibly without LINQ. To start with I created just one table/model/controller/view on basic ASP.net mvc template in VS2010(Just index page and Index method is implemented). I am currently going with try/error as all tutorials on the web are based on EF and I have an embedded c background.

My questions are:

  • Is the architecture correct?

  • I saw repository pattern is used in some open source projects such as nearforums. What's its advantage and how does it fit into this, does it replace DAL?

  • Should I pass datatables to view or objects representing the datatable?

  • Can I pass more than one model to razor page? How can I list 2 different tables for example?

  • Is it better to put all DAL code in one file?

DAL:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Configuration;
using MySql.Data.MySqlClient;

namespace MvcApplication1.Models
{
  public class DAL
  {
    public DAL()
    { }
    public DataTable getDataTable(string tableName)
    {
      using (MySqlConnection conn = new MySqlConnection(ConfigurationManager.ConnectionStrings["MySQLConn"].ConnectionString))
      {
        using (MySqlCommand command = conn.CreateCommand())
        {
          command.CommandText = "select * from " + tableName;
          command.CommandType = CommandType.Text;

          conn.Open();

          var table = new DataTable();
          table.Load(command.ExecuteReader());

          return table;
        }
      }
    }
  }
}

Product.cs class that represents Product table in the code:

namespace MvcApplication1.Models
{
  public class Product
  {
      public int ProductId { get; set; }
      public string Name { get; set; }
      public string Producer { get; set; }
      public int UnitPrice { get; set; }
  }
}

ProductController.cs

namespace MvcApplication1.Controllers
{
    public class ProductController : Controller
    {
        //
        // GET: /Product/
      DAL dal = new DAL();
        public ActionResult Index()
        {
          DataTable dt = dal.getDataTable("Product");
          Product[] products = new Product[dt.Rows.Count];
          for (int i = 0; i < dt.Rows.Count; i++)
          {
            products[i] = new Product();
            products[i].ProductId = (int)dt.Rows[i]["ProductId"];
            products[i].Name = (string)dt.Rows[i]["Name"];
            products[i].Producer = (string)dt.Rows[i]["Producer"];
            products[i].UnitPrice = Decimal.ToInt32((decimal)dt.Rows[i]["UnitPrice"]);
          }

          return View(products);
        }
........
........
}

Index.cshtml:

@model IEnumerable<MvcApplication1.Models.Product>
@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>
@foreach (var item in Model)
{
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.ProductId)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Name)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Producer)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.UnitPrice)
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id=item.ProductId }) |
            @Html.ActionLink("Details", "Details", new { id=item.ProductId }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.ProductId })
        </td>
        <br>
    </tr>
}

解决方案

I saw repository pattern is used in some open source projects such as nearforums. What's its advantage and how does it fit into this, does it replace DAL?

The benefits of the repository pattern are that it allows you to switch out your data access logic/ORM. For example, if you wanted to switch from Entity Framework to NHibernate, you just update your registrations inside you IoC container and like magic your code is using NHibernate with 0 knowledge of you ever making the switch. It allows your code to be agnostic of the underlying persistence framework. For all it knows, results code be coming from a file, web service call, or an in memory list. You'll also get reuse in the event that you had to make the same query from another component. Another gain is unit testing. With your current implementation, you cannot unit test your controller as it's going to connect directly to your database every time, thus by definition making it an integration test. You will certainly want to leverage an ORM, or you'll be writing the same code over and over again until it makes you cry. Setting up/tearing down connections, type casting all your primitives to native .NET types, etc. Dealing with native ADO.NET is a thing of the past nowadays. Make your life easier and use an ORM. At the same time, with great power comes great responsibility. ORMs can be a nightmare if you don't validate the queries that are being generated and executed against your database. If not used properly, they'll generate performance problems. You'll be able to leverage LINQ for most of your queries, but sometimes you'll have to get dirty funky native and go with raw SQL. You ORM will still be able to handle both scenarios.

Should I pass datatables to view or objects representing the datatable?

You certainly don't want to pass datatables. You want to pass view models or entities to your view. The view should know nothing about the database. All you do is give it data, and it displays in on the screen not ever knowing the source of that data. You want to be careful with passing entities directly to your view if you're using something like NHibernate, because you run into problems associated with lazy loading and N + 1 queries. View models are typically slimmed down versions of your entity. For example, if you had an entity with 4 properties but the view only needed to consume 2/4 of those properties, you'd make a separate view model with 2 properties and use a mapping library like Automapper to map from your entity to view model.

Can I pass more than one model to razor page? How can I list 2 different tables for example?

This is quite simple. You make a top level object and give it 2 properties to represent the entities you want to access.

public class MyViewModel
{
  public class Entity1 FirstObject { get; set; }

  public class Entity2 SecondObject { get; set; }
}

Then you'd make a strongly typed view and render FirstObject and SecondObject using the strongly typed view helpers you used in your razor view posted in your question. @Html.TextBoxFor(), etc.

Lastly, your controller would accept MyViewModel as an argument and populate FirstObject and SecondObject based on the form inputs rendered in your view.

Is it better to put all DAL code in one file?

You want to put related DAL code in the same file. Things are typically mapped out by table but that all depends on the relationships between your objects (what's your aggregate root for example). What you don't want to do is blindly implement one repository per table. You'll just end up with a really procedural and anemic data model that results in stitching together object graphs and relationships via multiple calls to the database. I'd recommend looking into Domain Driven Design to get a good idea on how to tackle this problem.

I've just scratched the surface here. You'll basically need to pick up the latest patterns and practices if you want to do this stuff properly. It's a different movement all together. Not like the good old days of monolithic code behind files, view state, and DataGrid controls. There are some really good books out there like:

Brownfield Application Development Domain Driven Design (Eric Evans) Clean Coder (Robert C Martin) Refactoring: Improving the Design of Existing Code (Martin Fowler) Patterns of Enterprise Application Architecture (Martin Fowler)

I'm not saying read all these books verbatim, but I'd strongly recommend the first 2. I'm sure the community will have even more to say about these development practices, but this is my perspective on it all. Thanks and good luck.

这篇关于ASP.NET MVC 4项目没有任何ORM的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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