Design Guidelines, Managed code and the .NET Framework
Over last month over the holidays, Lance Olson and I spent some time porting ScottGu's excellent MVC example over the Entity Framework. I thought I'd share the results here and get your thoughts\feedback.
12-11-08: I updated a few links and the example to match latest bits.
For this example, you will need:
If you are the type that likes to eat your desert first, you can skip to the end and just download the full working solution (Update: download this version of the sample that works with latest bits).
Getting Started<Category> categories = Northwind.Categories.ToList(); RenderView("Categories", categories);}
Next step, we need to create the "Categories" view..
Creating the View<Category> >
{
}.
<h2>Browse Products</h2>
<ul class="categorylisting">
<% foreach (var category in ViewData) { %>
<li>
<%= Html.ActionLink(category.CategoryName, new { action="List", id=category.CategoryName }) %>
</li>
<% } %>
</ul><Product><Product><Products>
public partial class ListingByCategory : ViewPage< List<Product> >
{
}
Next, to implement the view, we simply loop over the view data and spit it out in the right format.
<%--Print out the catagory name--%>
<% foreach (var product in ViewData) { %>
<% if (product.Category.CategoryName != null) { %>
<h2> <%=product.Category.CategoryName %></h2>
<% break; %>
<%} //end if %>
<%}//end foreach %>
<ul class="productlist">
<% foreach (var product in ViewData) { %>
<li>
<img src="/Content/Images/<%=product.ProductID%>.jpg" alt="<%=product.ProductName %>" />
<br/>
<a href="/Products/Detail/<%=product.ProductID %>"> <%=product.ProductName %> </a>
<br />
Price: <%=String.Format("{0:C2}", product.UnitPrice)%>
<span class="editlink"">
(<%= Html.ActionLink("Edit", new { Action="Edit", ID=product.ProductID })%>)
</span>
</li>
<% } %>
</ul>
Once you add the /Content/Images directory from the sample project you get this:
Unit Testing
One of the primary reasons for using the MVC model is to enable Test Driven Development and more generically Unit Testing. Unit testing UIs is notoriously difficult. Automation is fragile and hiring an army of testers to click on buttons is not always cost effective. The model MVC is going for is to separate out as much code (and therefore potential bugs) as possible into the Model and the Controller where they are testable.
So, we are going to write Unit Tests for the two control methods we just created and the corresponding logic in the model.
First, we need to setup our testing environment. The default template already created a Test project we can start to customize.
1. In the MvcApplicationTest project, create a new class called ProductControllerTest.cs
2. Add a method for testing the Categories action we defined above.
namespace MvcApplicationTest.Controllers
{
[TestClass]
public class ProductsControllerTest
{
[TestMethod]
public void Categories()
{
}
}
3. We want to test the controller we wrote, but we don't want to load IIS and all of ASP.NET... we want to have the leanest, most simple system we can to avoid test breaks, etc. To that end, I created a test specific subclass of the ProductsController we defined above. In this subclass I override the RenderView method. Instead of calling out to ASP.NET, my test specific implement simply captures the arguments so they can be queried later in the test.
class TestProductsController : ProductsController
{
public string ViewName { get; set; }
public string MasterName { get; set; }
public new object ViewData { get; set; }
protected override void RenderView(string viewName, string masterName, object viewData)
{
ViewData = viewData;
MasterName = masterName;
ViewName = viewName;
}
}
4. Now we implement the test! First we create an instance of our test controller, then I create some dummy (or mock) data. The idea here is that we don't want to hit the production database (or any database for that mater) in our tests. We want exactly the data we need for the test, no more, no less. Then we set up the NorthwindDataContext to use our data rather than the data from the database. Then we call the controller action we are trying to test. Finally, we assert a few things.. that the type of the ViewData is right, that the number of items returned is right, etc. Notice, you will need to add a reference to the EntityFramework (System.Data.Entity.dll) in your test project to use these EF generated types like Product, Category, etc.
[TestMethod]
public void Categories()
{
// Create Products Controller
TestProductsController controller = new TestProductsController();
List<Category> l = new List<Category>();
l.Add(new Category() { CategoryName = "Drink" });
l.Add(new Category() { CategoryName = "Food" });
l.Add(new Category() { CategoryName = "Cheese" });
controller.Northwind.TheCategories = l.AsQueryable();
// Invoke Controller Action
controller.Categories();
// Verify Detail Action Behavior
Assert.AreEqual(typeof(List<Category>),
controller.ViewData.GetType(),
"Product object Passed to View");
Assert.AreEqual(3,
((List<Category>)controller.ViewData).Count,
"Correct Number of Catagories returned");
Assert.AreEqual("Food",
((List<Category>)controller.ViewData)[1].CategoryName,
"Correct Product Object Passed to View");
Assert.AreEqual("Categories",
controller.ViewName,
"Correct View Rendered");
}
5. Set the connection string in the test project so that it access the metadata from EF model, but does not open the database. In MVCApplicationTest add an app.config file to the root of the project with the this connection string.
<?xml version="1.0"?>
<configuration>
<connectionStrings>
<add name="NorthwindEntities"
connectionString="metadata=res://*/;provider=System.Data.SqlClient;"
providerName="System.Data.EntityClient" />
</connectionStrings>
</configuration>
Now, we need to go back to the EDM designer and set it to embed the metadata for the model as part of the assembly. This makes our connection string above much more simple. Double click on the edmx file, then click on the conceptual model in the model browser and in the property sheet you change the property Metadata Artifact Processing from “Copy to Output Directory” to “Embed in Output Assembly”
6. Now we need to do just a bit of setup in the MVCApplication to enable a great testing experience... There are a few tricks here and what I am showing is NOT the definitive model (there isn't a definitive model yet)... but I like it, so what the heck!
MVCApplication/Model/NorthwindDataContext.cs add the following encapsulation of the Categories property.
private IQueryable<Product> savedProducts = null;
public IQueryable<Product> TheProducts
{
get
{
if (savedProducts == null) savedProducts = this.Products;
return savedProducts;
}
set
{
savedProducts = value;
}
}
Then, make sure that all access go through this abstraction. For example:
public List<Product> GetProductsByCategory(string category)
{
return TheProducts.Where(p => p.Category.CategoryName == category).ToList();
}
Finally, we need to make sure the NorthwindEntities is accessible from the test classes, so in ProductsController.cs add the "public" modifier.
public NorthwindEntities Northwind = new NorthwindEntities();
Now, we are able to run our test. You can do this by setting the test project as being the "startup project" (right click on the test project) or you can select Test/Run menu option.
Well, that is the lap around MVC+EF... There is a lot more to the sample I posted. If there is interest and I get the time, I will walk through the rest in future blog posts, but all the source code is there, so you can have fun with it on your own!
Enjoy!
You can download the full working example here (Updated to work with latest bits).
Some very good information here!
Carmelo Lisciotto
ASP.Net MVC Sample Application using ADO.Net Entity Framework By now, you already know that I like walkthoughs
You've been kicked (a good thing) - Trackback from DotNetKicks.com
Interesting read, very 'edgy' stuff: MVC + EF.
The tests in this example seem pretty useless to me, it's like your defining the outcome and then testing it, ofcourse it's good. Also, testing if the correct view is rendered is going to be Tedious!
Can you post a more realistic example, maybe something from your real work? Testing the 'hello world' scenarios is not really convincing me.
Lastly, the part about Metadata Artifact Processing could use some more explanation.
Thanks!
This is an excellent article on MVC however it would be great if you could include more specific example for instance how do you upload an image of the product using MVC architecture, and how to use thrid party controls such as Telerik or Infragistics.
Thank you
too complex
Cool......MVC+Entity Framework + Linq + Unit testing
Hi,
Any idea, when will it be possible to run such MVC applications on VWD 2008....?
Since VWD is an IDE, just any one can afford to download, i think, full support for this IDE is a must.
Thanks
Greetings,
I have been watching and noticing that you and increasingly many other developers are switching from VB to C# and it's variants.
Do you think there's that much future left for VB?
cheers,
Etienne
ASP.NET ASP.NET Hang and OutOfMemory exceptions caused by STA components [Via: Tess ] Code Camps New...
Link Listing - January 29, 2008
Great examples, although I would love to see more samples with user controls, and ajax. Two things I can't seem to wrap my mind around with in the MVC world.
Very good post :) I think the opening paragraphs need to explain (in layman's terms) the differences between LinqToSql and EF and why it might be appropriate to go EF or not. To me, this looks very very similar to LinqToSql so i'm not sure why i would use EF.
Secondly :-
"5. Set the connection string in the test project so that it access the metadata from EF model, but does not open the database".
It think this needs to be explained a bit more -> what does it mean, why would you do that?
Nice guys :)
Oh - one more thing to add.
Please show us how we could do a simple MVC View User Control that has some 'actions' associated to it. Eg, a listing all the products, and the action could be a 'sort by' or 'order by' action or a filter action .. all wrapped up in a resusable MVC View User Control.
Cheers!
Hello, i can't download the full solution, my browser wrote adress not found, maybe link dead, or need some registration ?
Hello,
Same problem here, impossible to download the full solution archive.
It would be very kind if you could fix the link.
Thank you very much !
Very cool! In my humble opinion, MVC+EF (+TDD) can really change the game, so the unit testing part is my favorite here. Agree with what PK said, there seems to be extremely little document on EF, so distinguishing it from LingtoSQL will be good. More importantly, I would like to know unit testing without connecting to the database. What did it really do when you change from “Copy to Output Directory” to “Embed in Output Assembly”? If I have a Entity data model created from scratch (not from a database), would it enable me to use the EDM independently as an in-memory store?
Thanks and great work!
Change to "Embed in Output Assembly" doesn't seem to disconnect the EDM from the underlying database. Just tried:).
Played around for a couple of hours now, but am still confused on how to access the model without opening the DB. Any suggestions?
On why I want to do it? Besides making the testing simple as mentioned in the post; I also want to design the model ahead of the DB tables. Just want to get the program running, then later map the model to a database (manually? is it possible to generate schema from an entity model?).
Thanks,
@PK - Check out this article on MSDN: Introducing LINQ to RElational Data [] to get an idea of when you would use LINQ to SQL vs. when you would use EF.
@jnw - When you embed, you are embedding the schema files so you don't have to copy them around. Mike Pizzo recently demo'd starting from an empty model in this webcast []. It's the first demo.
hth
julie
Thanks a lot Julie.
In case someone is also curious about testing without "opening the database", the answer lies in the step 6 (not step 5) of the Unit testing part.
Thanks for the great post.
It started an email Mohamed Hossam (AKA, Bashmohandes) sent to my company's local office here in Egypt
Resumo da semana - 07/02/2008
For the past year, there seems to be an overwhelming community outcry for getting back to a simpler separation...
首先,谢谢TerryLee的推荐系列,本文就是在他的推荐系列看到的.
原文地址:ASP.NETMVCExampleApplicationoverNorthwindwiththeEnt...
导读：来自于Brad Abrams 的一篇很棒的入门文章，使用ASP.NET MVC Framework和ADO.NET Entity Framework开发一个简单的示例，延续了Brad Abrams 的一贯风格，图文并茂，相信对于初学者朋友有很大的帮助。(引用一下TerryLee的导读,^_^)
What about validation? Validation Application Block?
As some else suggested, what about ajax? Customers are increasing asking about the UI and Ajax. How does MVC deal with this?
Looks like Html.ActionLink has changed in the March CTP. Your samples break pretty consistently there. It isn't mentioned in the release notes...
He adaptado para Visual Web Developer Express una de las aplicaciones de ejemplo para ASP.NET MVC que
Great example and a good introduction to EF and ASP.net MVC !
I upgrade your sample to works with the latest version of ASP.net MVC (ASP.Net MVC Preview 2) and publish it on code.msdn.microsoft.com
whilst asp.net mvc affords testability, the entity framework DOES NOT! POJO is not supported and you cannot swap out the EF's control over the persistence mechanism. I don't see the point of using the MVC for testability, when your tests will still have and end to end reliance on the EF with DB access. It is possible tobreak this dependency which much work, and it simply looks like EF has not been designed with testability in mind.
Over last month over the holidays, Lance Olson and I spent some time porting ScottGu's excellent MVC example over the Entity Framework . I thought I'd share the results here and get your thoughts\feedback. For this example, you will need: VS2008 (Fre
先来发一通牢骚。 其实这是一篇迟发布近2个月的文章。事实上在ASP.NETMVCPreview2发布之前我就已经将这篇文章的所有内容准备完毕了。当时想，就等Preview2发布吧，而真一...
原文地址:...