Sorted By: Month (12) and Year (2011)

ASP.NET MVC Code Review #2 - A Way of Working with Html Select Element (AKA DropDownList) In ASP.NET MVC

This is the #2 of the series of blog posts which is about some core scenarios on ASP.NET MVC: A Way of Working with Html Select Element (AKA DropDownList) In ASP.NET MVC
2011-12-30 14:28
Tugberk Ugurlu


This is the #2 of the series of blog posts which is about some core scenarios on ASP.NET MVC. In this one, code review #2, I will try to show you the best way of working with Html Select element (AKA DropDownList) in ASP.NET MVC. Here is the code:

Repository Class which generates the dummy data for the demo:

public class ProductCategory {

    public int CategoryId { get; set; }
    public string CategoryName { get; set; }
}

public class ProductCategoryRepo {

    public List<ProductCategory> GetAll() {

        List<ProductCategory> categories = new List<ProductCategory>();

        for (int i = 1; i <= 10; i++) {

            categories.Add(new ProductCategory { 
                CategoryId = i,
                CategoryName = string.Format("Category {0}", i)
            });
        }

        return categories;
    }
}

Controller:

public class SampleController : Controller {

    private readonly ProductCategoryRepo productCategoryRepo = 
         new ProductCategoryRepo();

    public ActionResult Index() {

        registerProductCategorySelectListViewBag();
        return View();
    }

    private void registerProductCategorySelectListViewBag() {

        ViewBag.ProductCategorySelectList = 
            productCategoryRepo.GetAll().Select(
                c => new SelectListItem { 
                    Text = c.CategoryName,
                    Value = c.CategoryId.ToString()
                }
            );
    }
}

View:

@{
    ViewBag.Title = "HTML Select List Sample";
}

<h2>HTML Select List Sample</h2>

<p>
    <strong>Product Categories:</strong>
</p>
<p>
    @Html.DropDownList(
        "ProductCategoryId", 
        (IEnumerable<SelectListItem>)ViewBag.ProductCategorySelectList
    )
</p>

Let’s see what it generates for us:

Output HTML of Select element:

<select id="ProductCategoryId" name="ProductCategoryId">
    <option value="1">Category 1</option>
    <option value="2">Category 2</option>
    <option value="3">Category 3</option>
    <option value="4">Category 4</option>
    <option value="5">Category 5</option>
    <option value="6">Category 6</option>
    <option value="7">Category 7</option>
    <option value="8">Category 8</option>
    <option value="9">Category 9</option>
    <option value="10">Category 10</option>
</select>

Just like what I expected. On the controller, you see that I newed up SelectListItem classes and pass them to the view through the ViewDataDictionary. SelectListItem class works nicely with DropDownList and DropDownListFor Html helpers within ASP.NET MVC as you see inside the view code above.

So, don’t try to reinvent the wheel and don’t get into for and foreach loops in order just to create a select element. SelectListItem has been put inside the library just for this purpose and leverage it.

ASP.NET MVC Code Review #1 - File Upload With HttpPostedFileBase Class

This is #1 of the series of blog posts which is about some core scenarios on ASP.NET MVC: File Upload With HttpPostedFileBase Class
2011-12-29 21:25
Tugberk Ugurlu


Today, I decided to change my blogging style a little bit. I always try to write posts which contains detailed information about the subject but I realized that it prevents me from writing much more useful things. So, from now on, I will drop a bunch of code on the screen and talk about that briefly.

This is the beginning of the series of blog posts which is about some core scenarios on ASP.NET MVC. In this one, code review #1, I will give you an example on how to get file upload functionality working in ASP.NET MVC. Here is the code:

Controller:

public class SampleController : Controller {

    public ActionResult Index() {
        return View();
    }

    [ActionName("Index")]
    [ValidateAntiForgeryToken, HttpPost]
    public ActionResult Index_post(HttpPostedFileBase File) {

        //Check if the file is not null and content length is bigger than 0
        if (File != null && File.ContentLength > 0) {

            //Check if folder is there
            if(!System.IO.Directory.Exists(Server.MapPath("~/Content/PostedFiles")))
                System.IO.Directory.CreateDirectory(
                    Server.MapPath("~/Content/PostedFiles")
                );

            //Set the full path
            string path = System.IO.Path.Combine(
                Server.MapPath("~/Content/PostedFiles"),
                System.IO.Path.GetFileName(File.FileName)
            );

            //Save the thing
            File.SaveAs(path);

            TempData["Result"] = "File created successfully!";
        }

        //RedirectToAction so that we can get rid of so-called "Form Resubmission"
        return RedirectToAction("Index");
    }

}

View:

@{
    ViewBag.Title = "File Upload Sample";
}
<h2>File Upload Sample</h2>

@if (TempData["Result"] != null) { 
    <ul>
        <li>@TempData["Result"]</li>
    </ul>
}

@using (Html.BeginForm("index", "sample", 
    FormMethod.Post, new { enctype = "multipart/form-data" })) {
 
    @Html.AntiForgeryToken()
    
    <input type="file" name="File" />
    <p>
        <input type="submit" value="Upload" />
    </p>
}

Actually, code explains itself nicely here but I see one thing to worth pointing out here. HttpPostedFileBaseModelBinder class from System.Web.Mvc namespace is the class which binds a model to a posted file. So, the parameter (which is type of HttpPostedFileBase) of the Index_post method receives the posted file.

Pretty neat stuff. Hope you enjoy it.

How to Work With Generic Repositories on ASP.NET MVC and Unit Testing Them By Mocking

In this blog post we will see how to work with generic repositories on ASP.NET MVC and unit testing them by mocking with moq
2011-12-22 17:05
Tugberk Ugurlu


image

I have blogged about Generic Repository Pattern - Entity Framework, ASP.NET MVC and Unit Testing Triangle but that blog post only contains how we can implement that pattern on our DAL (Data Access Layer) project. Now, let’s see how it fits into our ASP.NET MVC application.

I created a sample project which basically has CRUD operations for Foo class and I put the complete code of the project on GitHub. https://github.com/tugberkugurlu/GenericRepoWebApp

So, in the previous blog post we have created our DAL project and repository classes based on our generic repository. I have created an ASP.NET MVC 3 Web Application project and a Visual Studio Test Project besides the DAL project. On the left had side, you can see how the project structure looks like inside solution explorer.

When we think about the project, we have repository classes which implements GenericRepositroy<C, T> abstract class and individual repository interfaces. So, we need a way to inject our concrete repository classes into our ASP.NET MVC application so that we make our application loosely coupled which means unit testing friendly.

Fortunately, ASP.NET MVC has been built with unit testing in mind so it makes dependency injection very easy with DependencyResolver class. DependencyResolver class Provides a registration point for dependency resolvers that implement IDependencyResolver or the Common Service Locator IServiceLocator interface. But we won’t be dealing with that class at all. Instead, we will use a third party dependency injector called Ninject. Ninject also has a package which benefits from DependencyResolver of ASP.NET MVC. We will use Nuget to bring down Ninject.

image

After we install the package, we will see a folder named App_Start added to our project. Inside that folder, open up the NinjectMVC3.cs file and go to RegisterServices method. In our case, here what we do:

/// <summary>
/// Load your modules or register your services here!
/// </summary>
/// <param name="kernel">The kernel.</param>
private static void RegisterServices(IKernel kernel) {

    kernel.Bind<IFooRepository>().To<FooRepository>();
    kernel.Bind<IBarRepository>().To<BarReposiltory>();
}

This does some stuff behind the scenes and I won’t go into details here but I really recommend you to go and take a look at series of blog posts which Brad Wilson has done on ASP.NET MVC 3 Service Location. However, if we try to explain it with simplest words, Ninject news up the controller classes with parameters which we specify. In this case, if a controller constructor accepts a parameter which is type of IFooRepository, Ninject will give it FooRepository class and news it up. We will see why this is useful on unit testing stage.

When we look inside the RegisterServices method, we don’t see neither GenericRepository nor IGenericRepository because the way we implement them enables them to work behind the scenes.

As for the implementation, here how the controller looks like:

public class FooController : Controller {

    private readonly IFooRepository _fooRepo;
    
    public FooController(IFooRepository fooRepo) {
        _fooRepo = fooRepo;
    }

    public ViewResult Index() {

        var model = _fooRepo.GetAll();
        return View(model);
    }

    public ActionResult Details(int id) {

        var model = _fooRepo.GetSingle(id);
        if (model == null)
            return HttpNotFound();

        return View(model);
    }

    public ActionResult Edit(int id) {

        var model = _fooRepo.GetSingle(id);
        if (model == null)
            return HttpNotFound();

        return View(model);
    }

    [ActionName("Edit"), HttpPost]
    public ActionResult Edit_post(Foo foo) {

        if (ModelState.IsValid) {

            try {
                _fooRepo.Edit(foo);
                _fooRepo.Save();

                return RedirectToAction("details", new { id = foo.FooId });

            } catch (Exception ex) {
                ModelState.AddModelError(string.Empty, "Something went wrong. Message: " + ex.Message);
            }
        }

        //If we come here, something went wrong. Return it back.
        return View(foo);
    }

    public ActionResult Create() {

        return View();
    }

    [ActionName("Create"), HttpPost]
    public ActionResult Create_post(Foo foo) {

        if (ModelState.IsValid) {

            try {
                _fooRepo.Add(foo);
                _fooRepo.Save();

                return RedirectToAction("details", new { id = foo.FooId });

            } catch (Exception ex) {
                ModelState.AddModelError(string.Empty, "Something went wrong. Message: " + ex.Message);
            }
        }

        //If we come here, something went wrong. Return it back.
        return View(foo);

    }

    public ActionResult Delete(int id) {

        var model = _fooRepo.GetSingle(id);
        if (model == null)
            return HttpNotFound();

        return View(model);
    }

    [ActionName("Delete"), HttpPost]
    public ActionResult Delete_post(int id) {

        var model = _fooRepo.GetSingle(id);
        if (model == null)
            return HttpNotFound();

        _fooRepo.Delete(model);
        _fooRepo.Save();

        return RedirectToAction("Index");
    }
}

All of the action methods do some very basic stuff but one thing to notice here is the below code:

    private readonly IFooRepository _fooRepo;
    
    public FooController(IFooRepository fooRepo) {
        _fooRepo = fooRepo;
    }

As I mentioned before, controller constructor accepts a parameter which is type of IFooRepository and inside the constructor method, we expose the parameter for internal use of that controller class.

I have some views which corresponds to each action method and they work as expected.

Unit Testing

So, how do we unit test that controller without connecting to our database? When we think theoretically, what we need is a fake repository which implements IFooRepository interface so that we can pass that fake repository into our controller as a constructor parameter. Pay attention here that we still has no need for neither generic repository interface nor generic repository abstract class. We just need to fake FooRepository interface with fake data.

We will do this by mocking and creating mock objects. In order to do that, we will benefit from an awesome library called Moq.

As you can see inside the project on GitHub, I didn’t use NuGet to bring down the Moq because I tried and it failed over and over again. So, I put that inside the lib folder under the root directory and reference it from there.

After you reference the Moq library inside the Test application, create a class named FooControllerTest.cs. Here how it should look like at first:

[TestClass]
public class FooControllerTest {

}

So empty. We will start to fill it in with a mock of IFooReporsitory. Below, you can see the complete code which enables that:

[TestClass]
public class FooControllerTest {

    private IFooRepository fooRepo;

    [TestInitialize]
    public void Initialize() {

        //Mock repository creation
        Mock<IFooRepository> mock = new Mock<IFooRepository>();
        mock.Setup(m => m.GetAll()).Returns(new[] { 
            new Foo { FooId = 1, FooName = "Fake Foo 1" },
            new Foo { FooId = 2, FooName = "Fake Foo 2" },
            new Foo { FooId = 3, FooName = "Fake Foo 3" },
            new Foo { FooId = 4, FooName = "Fake Foo 4" }
        }.AsQueryable());

        mock.Setup(m => 
            m.GetSingle(
                It.Is<int>(i => 
                    i == 1 || i == 2 || i == 3 || i == 4
                )
            )
        ).Returns<int>(r => new Foo { 
            FooId = r,
            FooName = string.Format("Fake Foo {0}", r)
        });

        fooRepo = mock.Object;
    }

}

This Initialize method will run before all of the test methods run so we can work inside that method in order to mock our object.

In here, first I have setup a mock for GetAll method result and it returns 4 instances or Foo class.

Second, I do the same thing for GetSingle method. It looks a little different because it accepts a parameter type of int. What I am telling there is that: there are 4 instances I have here and if the parameter matches one of those instances, it will returns a Foo class which is a type of GetSingle method returns.

Lastly, I expose the mock object for internal use for the test class.

Now we have an IFooRepository instance we can work with. We have completed the hard part and now we can start writing our unit tests. Here is some of possible unit tests that we can have:

[TestClass]
public class FooControllerTest {

    private IFooRepository fooRepo;

    [TestInitialize]
    public void Initialize() {

        //Mock repository creation
        Mock<IFooRepository> mock = new Mock<IFooRepository>();
        mock.Setup(m => m.GetAll()).Returns(new[] { 
            new Foo { FooId = 1, FooName = "Fake Foo 1" },
            new Foo { FooId = 2, FooName = "Fake Foo 2" },
            new Foo { FooId = 3, FooName = "Fake Foo 3" },
            new Foo { FooId = 4, FooName = "Fake Foo 4" }
        }.AsQueryable());

        mock.Setup(m => 
            m.GetSingle(
                It.Is<int>(i => 
                    i == 1 || i == 2 || i == 3 || i == 4
                )
            )
        ).Returns<int>(r => new Foo { 
            FooId = r,
            FooName = string.Format("Fake Foo {0}", r)
        });

        fooRepo = mock.Object;
    }

    [TestMethod]
    public void is_index_returns_model_type_of_iqueryable_foo() {
        
        //Arrange
        //Create the controller instance
        FooController fooController = new FooController(fooRepo);

        //Act
        var indexModel = fooController.Index().Model;

        //Assert
        Assert.IsInstanceOfType(indexModel, typeof(IQueryable<Foo>));
    }

    [TestMethod]
    public void is_index_returns_iqueryable_foo_count_of_4() {

        //Arrange
        //Create the controller instance
        FooController fooController = new FooController(fooRepo);

        //Act
        var indexModel = (IQueryable<object>)fooController.Index().Model;

        //Assert
        Assert.AreEqual<int>(4, indexModel.Count());
    }

    [TestMethod]
    public void is_details_returns_type_of_ViewResult() {

        //Arrange
        //Create the controller instance
        FooController fooController = new FooController(fooRepo);

        //Act
        var detailsResult = fooController.Details(1);

        //Assert
        Assert.IsInstanceOfType(detailsResult, typeof(ViewResult));
    }

    [TestMethod]
    public void is_details_returns_type_of_HttpNotFoundResult() { 

        //Arrange
        //Create the controller instance
        FooController fooController = new FooController(fooRepo);

        //Act
        var detailsResult = fooController.Details(5);

        //Assert
        Assert.IsInstanceOfType(detailsResult, typeof(HttpNotFoundResult));
    }
}

When I run the all the test, I should see all of them pass and I do:

image

I hope this blog post gives you an idea. Stay tuned for others Winking smile

NOTE:

Entity Framework DbContext Generic Repository Implementation Is Now On Nuget and GitHub: http://www.tugberkugurlu.com/archive/entity-framework-dbcontext-generic-repository-implementation-is-now-on-nuget-and-github

Generic Repository Pattern - Entity Framework, ASP.NET MVC and Unit Testing Triangle

We will see how we can implement Generic Repository Pattern with Entity Framework and how to benefit from that.
2011-12-22 09:07
Tugberk Ugurlu


IMPORTANT NOTE:

I have a new blog post about Generic Repository implementation for Entity Framework. Please check it out instead of this one: Clean, Better, and Sexier Generic Repository Implementation for Entity Framework

NOTE:

Entity Framework DbContext Generic Repository Implementation Is Now On Nuget and GitHub: http://www.tugberkugurlu.com/archive/entity-framework-dbcontext-generic-repository-implementation-is-now-on-nuget-and-github

DRY: Don’t repeat yourself which is a principle of software development aimed at reducing repetition of information of all kinds, especially useful in multi-tier architectures. That’s what Wikipedia says. In my words, if you are writing the same code twice, follow these steps:

  • Step back.
  • Sit.
  • Think about it and dwell on that.

That’s what I have done for repository classes on my DAL projects. I nearly all the time use Entity Framework to reach out my database and I create repositories in order to query and manipulate data inside that database. There are some specific methods which I use for every single repository. As you can assume, those are FindBy, Add, Edit, Delete, Save. Let’s see on code what is my story here.

First approach (worst approach)

At first, long time ago, I have been creating all the single methods for each interface. For example below one is one of my repository interfaces:

I am giving the examples here with EF 4.2 but I was following this approach with EF 4 which does not contain DbContext class.

public interface IFooRepository {
        
    IQueryable<Foo> GetAll();
    Foo GetSingle(int fooId);
    IQueryable<Foo> FindBy(Expression<Func<Foo, bool>> predicate);
    void Add(Foo entity);
    void Delete(Foo entity);
    void Edit(Foo entity);
    void Save();
}

This repo is for Foo class I have (imaginary). Let's see the implementation for Bar class.

public interface IBarRepository {
    
    IQueryable<Bar> GetAll();
    Bar GetSingle(int barId);
    IQueryable<Bar> FindBy(Expression<Func<Bar, bool>> predicate);
    void Add(Bar entity);
    void Delete(Bar entity);
    void Edit(Bar entity);
    void Save();
}

Implementation nearly exactly the same here. Here is also an example of implementing one of these interfaces:

public class FooRepository : IFooRepository {

    private readonly FooBarEntities context = new FooBarEntities();

    public IQueryable<Foo> GetAll() {

        IQueryable<Foo> query = context.Foos;
        return query;
    }

    public Foo GetSingle(int fooId) {

        var query = this.GetAll().FirstOrDefault(x => x.FooId == fooId);
        return query;
    }

    public void Add(Foo entity) {

        context.Foos.Add(entity);
    }

    public void Delete(Foo entity) {

        context.Foos.Remove(entity);
    }

    public void Edit(Foo entity) {

        context.Entry<Foo>(entity).State = System.Data.EntityState.Modified;
    }

    public void Save() {

        context.SaveChanges();
    }
}

Also imagine this implementation for BarRepository as well. Indeed, there would be probably more repository classes for your project. After playing like that for a while I decided to do something different which still sucked but better.

A better approach but still sucks

I created a generic interface which saves me a lot of keystrokes. Here how it looks like:

public interface IGenericRepository<T> where T : class {
    
    IQueryable<T> GetAll();
    IQueryable<T> FindBy(Expression<Func<T, bool>> predicate);
    void Add(T entity);
    void Delete(T entity);
    void Edit(T entity);
    void Save();
}

And how I implemented in on repository interfaces:

public interface IFooRepository : IGenericRepository<Foo> {
    
    Foo GetSingle(int fooId);
}
public interface IBarRepository : IGenericRepository<Bar> {
    
    Bar GetSingle(int barId);
}

You can see that I only needed to implement GetSingle method here and others come with IGenericRepositoy<T> interface.

Where I implement these repository interfaces to my concrete classes, I still need to go over all the methods and create them individually. The repository class looked like as the same. So it leads me to a final solution which is the best one I can come up with so far.

Best approach

The generic interface I have created is still legitimate and usable here. In fact, I won’t touch the repository interfaces at all. What I did here first is to create an abstract class which implements IGenericReposity<T> interface but also accepts another type parameter defined in a generic declaration which is a type of DbConetxt class. Here is how it looks like:

public abstract class GenericRepository<C, T> : 
    IGenericRepository<T> where T : class where C : DbContext, new() {

    private C _entities = new C();
    public C Context {

        get { return _entities; }
        set { _entities = value; }
    }

    public virtual IQueryable<T> GetAll() {

        IQueryable<T> query = _entities.Set<T>();
        return query;
    }

    public IQueryable<T> FindBy(System.Linq.Expressions.Expression<Func<T, bool>> predicate) {

        IQueryable<T> query = _entities.Set<T>().Where(predicate);
        return query;
    }

    public virtual void Add(T entity) {
        _entities.Set<T>().Add(entity);
    }

    public virtual void Delete(T entity) {
        _entities.Set<T>().Remove(entity);
    }

    public virtual void Edit(T entity) {
        _entities.Entry(entity).State = System.Data.EntityState.Modified;
    }

    public virtual void Save() {
        _entities.SaveChanges();
    }
}

This is so nice because of some factors I like:

  • This implements so basic and ordinary methods
  • If necessary, those methods can be overridden because each method is virtual.
  • As we newed up the DbContext class here and expose it public with a public property, we have flexibility of extend the individual repositories for our needs.
  • As we only implement this abstract class only to our repository classes, it won’t effect unit testing at all. DbContext is not in the picture in terms of unit testing.

So, when we need to implement these changes to our concrete repository classes, we will end up with following result:

public class FooRepository :
    GenericRepository<FooBarEntities, Foo>, IFooRepository {

    public Foo GetSingle(int fooId) {

        var query = GetAll().FirstOrDefault(x => x.FooId == fooId);
        return query;
    }
}
public class BarReposiltory : 
    GenericRepository<FooBarEntities, Bar>, IBarRepository  {

    public Bar GetSingle(int barId) {

        var query = Context.Bars.FirstOrDefault(x => x.BarId == barId);
        return query;
    }
}

Very nice and clean. Inside BarRepository GetSingle method, as you see I use Context property of GenericRepository<C, T> abstract class to access an instance of DbContext.

So, how the things work inside our ASP.NET MVC project? this is another story but no so complicated. I will continue right from here on my next post.

UPDATE:

Here is the next post:

How to Work With Generic Repositories on ASP.NET MVC and Unit Testing Them By Mocking

Make The Visual Studio Extensions Compatible With Visual Studio 11 Developer Preview

Do you use Visual Studio 11 Developer Preview and miss your extensions? Well, I do! Especially, ADO.NET C# DbContext Generator. We'll see how to make them compatible with Visual Studio 11 Dev. Preview
2011-12-07 14:05
Tugberk Ugurlu


works-on-my-machine-seal-of-approvalDo you use Visual Studio 11 Developer Preview and miss your extensions? Well, I do! Especially, ADO.NET C# DbContext Generator.

As you know, for now Visual Studio extensions are not compatible with Visual Studio 11 Developer Preview.

image

This is normal because it is Developer Preview. Even, I opened up a thread for that on Stackoverflow: Visual Studio Extensions and Visual Studio 11 Dev. Preview and @betty replied to my post after a long time with an amazing answer. I never developed a Visual Studio extension before and I am not familiar with the drill so I thought it is not possible to tweak the extensions so that they can be compatible with Visual Studio 11 Developer Preview but it turns out that it is as easy as pie. How so? Here are the steps:

Oww, by the way, this thing works on my machine and I am not guarantee that it will work on yours as well. Even worse, it can completely screw your machine up. So, take the risk here and don’t swear to me.

I also assume that the ADO.NET C# DbContext Generator does not integrate with Visual Studio that much so there was no big compatibility problems but I won’t try this for the extensions like VSCommands 2010, Web Essentials, etc. If you try, please let me know how it went. Anyway, here is the drill:

First of all, download the extension from Visual Studio Gallery.

image

I am not sure if you are aware of it but vsix files are actually zip files just like NuGet package files (nupkg) and MS Word files (docx). So, change the extension of the file we have downloaded from vsix to zip:

image image

Unzip the zip file and you will see a file called extension.vsixmanifest under root folder. No, it is not a zip file, too Open-mouthed smile It is an xml file though. Open it up with a text editor and find the node called SupportedProducts:

image

Just change the value of version attribute of VisualStudio node to 11.0 and save it.

image

This is actually enough for the extension compatibility standpoint but ADO.NET C# DbContext Generator extension has some dependencies which are specific to Visual Studio 2010 (not sure on that though). So,we have one more step to go as well.

Navigate to /T/code/ folder and you will see a zip file there:

image

Unzip it:

image

Open up the file called ADONETArtifactGenerator_DbContextCSharp.vstemplate with a text editor this time and you will notice a node like below:

  <WizardExtension>
    <Assembly>Microsoft.Data.Entity.Design, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</Assembly>
    <FullClassName>Microsoft.Data.Entity.Design.VisualStudio.ModelWizard.AddArtifactGeneratorWizard</FullClassName>
  </WizardExtension>

Change this one with the below code:

  <WizardExtension>
    <Assembly>Microsoft.Data.Entity.Design, Version=11.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</Assembly>
    <FullClassName>Microsoft.Data.Entity.Design.VisualStudio.ModelWizard.AddArtifactGeneratorWizard</FullClassName>
  </WizardExtension>

Don’t ask me why because I have no clue. I assumed that it was a versioning issue and it works this way. Remember, this is developer preview. Not even alpha or beta so don’t look for logic that much.

Save the file and zip it up again.

image,

Don’t forget to delete other files. You just need that zip file inside the code folder.

Lastly, go under the root and zip all the files:

image

image

Now we have a zip file again. Change the extension from zip to vsix and double click on that

imageimage

Now we get it working smoothly:

imageimage

Now when you want to continue you way with database first approach, you can follow the steps which are explained here:

http://blogs.msdn.com/b/adonet/archive/2011/11/01/ef-4-2-released.aspx

Here is the quote from that blog post:

Model First & Database First Templates

The templates for using the DbContext API with Model First and Database First are now available under the “Online Templates” tab when “Right-Click –> Add Code Generation Item…” is selected on the EF Designer.

Instead of navigating to "Online Templates" tab, you will find the code gen. file under the "Code" tab:

image

Admit it, we totally nailed that thing Winking smile

Tags