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