locked
DAO Layer With MVC and Entity Framework - Should Use DAO and How? RRS feed

  • Question

  • HI Team,

    My client want to use a DAO layer with our MVC and Entity Framework implementation.

    We are writing a Custom ASP.NET application that would do CRUD operation on SQL database and display the data in aspx pages. Also we would write some web services that will read data from a text file kept at shared location and write that data to sql db.

    My question is:

    1) Should we use a DAO with Entity, is it a best practice with situation like above?

    2) How to implement DAO with Entity Framework, what class would be writen and will that site with MODEL?

    Please do not send the links to site, i tried googling and non of them is up to date. Can you please explain with a little answer.

    manoj.verma1n1@gmail.com is my gmail id or write here itself.

     


    manoj.verma
    • Moved by Min Zhu Thursday, February 2, 2012 3:21 AM (From:.NET Platform Architecture Development Discussions)
    Tuesday, January 31, 2012 9:33 AM

All replies

  • Any one.....why is that 51 ppl came and none of them replied?
    manoj.verma
    Wednesday, February 1, 2012 7:26 AM
  • I think there might be some confusion on the acronym you are using: "DAO". Do you mean "DAL" as in Data Access Layer? If yes, data access is done in the Model layer in MVC and using the Entity Framework is a great idea if you like using an ORM. The following link which does apply has a full tutorial on using the Entity Framework with ASP.NET MVC.

    Creating Model Classes with the Entity Framework (C#):
    http://www.asp.net/mvc/tutorials/older-versions/models-(data)/creating-model-classes-with-the-entity-framework-cs

    If you do not like the link above please post back because this is an often discussed topic with many current tutorials using EF and MVC.


    Thank you,
    Wednesday, February 1, 2012 4:59 PM
  • Hi Manoj.verma,

    I have moved this thread to Architecture General forum to help you get better support.

    Have a nice day!


    Min Zhu [MSFT]
    MSDN Community Support | Feedback to us
    Thursday, February 2, 2012 3:22 AM
  • Yes please, any one?

    Can I create a DAO this way and use it with MVC and Entity Framework?: 

    1)    First we will declare an all general purpose interface called IDAO from which all the other DAO interfaces will descend. It would declare the possible method like Save(for adding / updating an entity), Delete(for deleting an entity) , SaveChanges( to persist the changes) and more.

    Example:

    public interface IDao<TEntity>

    {

        TEntity Save(TEntity entity);

        void Delete(TEntity entity);

        void SaveChanges();

    }

     

    2)    Implement the method that each Entity would use.

     

    Example:

     

    public interface Ientity1Dao : IDao< entity1>

    { }

     

    public interface Ientity2Dao : Ientity1Dao

    {

        IEnumerable<entity2> Getentity2 ();

        IEnumerable<entity2> OtherMethodentity2 ();

    }

     

    public interface Ientity3Dao : Ientity1Dao

    {

        IEnumerable<Ientity3> GetIentity3();

    }

     

    public interface Ientity4Dao: IDao<Ientity4>

    {

        IEnumerable<Ientity4> GetIentity4();

    }

     

    3)    The business logic layer should not instantiate the DAO’s directly, achieve this using the factory class .

    For Example:

     

    public interface IDaoFactory

    {

        Ientity1Dao GetIentity1();

        Ientity2Dao GetIentity2();

        Ientity3Dao GetIentity3();

        Ientity4Dao GetIentity4();

    }

     

    4)    A helper class and an extension method will be used for the object of type ‘ObjectContext’ .Each DAO object will share the same ObjectContext in order to communicate with the Entity Data Model.

    The ObjectContextManager class provides a static Context property which will always return the same ObjectContext instance.

    The ‘GetEntitySetName()’ extension method of the ObjectContext type returns the entity set name of a given entity. This extension method queries the Entity Framework’s metadata in order to retrieve the entity set name.

    Example:

    public static class ObjectContextExtensions

    {

        public static string GetEntitySetName(this ObjectContext context, string entityTypeName)

        {

            var container = context.MetadataWorkspace.GetEntityContainer(context.DefaultContainerName, DataSpace.CSpace);

            string entitySetName = (from meta in container.BaseEntitySets

                                    where meta.ElementType.Name == entityTypeName

                                    select meta.Name).FirstOrDefault();

            return entitySetName;

        }

    }

    5)    If required, we would encapsulate/write an abstract base class to implement the DAInterface.

    Example:

    public abstract class EntityDao<TEntity> : IDao<TEntity> where TEntity : EntityObject, new()

    {

        protected ProjectsEntities Context

        {

            get

            {

                return ObjectContextManager.Context;

            }

        }

     

        private string entitySetName;

        protected string EntitySetName

        {

            get

            {

                if (String.IsNullOrEmpty(entitySetName))

                {

                    entitySetName = Context.GetEntitySetName(typeof(TEntity).Name);

                }

                return entitySetName;

            }

        }

     

      

     

        public TEntity Save(TEntity entity)

        {

            Context.AddObject(EntitySetName, entity);

            SaveChanges();

            return entity;

        }

     

        public void Delete(TEntity entity)

        {

            Context.DeleteObject(entity);

            SaveChanges();

        }

     

        public void SaveChanges()

        {

            Context.SaveChanges();

        }

     

      }

     

    6)    Now the Dao’s ready to be used.

     


    manoj.verma
    Thursday, February 2, 2012 10:17 AM
  • Any one, seems like a tough dicission to all. 137 views and no perfect answer. Atleast let me know of above DAO that I created will work with MVC and Entity Framework or not?
    manoj.verma
    Friday, February 3, 2012 4:13 AM
  • Any one to validate?
    manoj.verma
    Monday, February 6, 2012 2:31 AM
  • I have not used EF enough to say if you are breaking any rules specific to that, but as far as how you have set up your Data Access Interface, Implementations, access from the BLL (I use DI for this myself), and extentions all look fine.

    I think the main reason you have not received too much help is because the question is so broad. Asking specific questions rather than trying to have an entire layer's code validated works much better on the forums. Regardless, from what I see your code looks good to me. There are always 20 different ways to accomplish the same thing in .NET, and I don't see anything wrong with your approach.


    Thank you,
    Monday, February 6, 2012 2:17 PM
  • atconway is right that the confusion is over the term "DAO". The term data access object refers to a domain object typically, but what you seem to actually be talking about is a DAL - a layer to actually save and load these objects. You also put in the title that you're talking about MVC with EF, but then you mention you're displaying data in aspx pages, which don't exist in MVC. I think people are confused about what you're really asking.

    On the assumption that you're talking about MVC and using the Entity Framework, and that you're asking whether you should have a separate data access layer and DTOs rather than using the EF-generated domain classes, the real answer is "it depends".

    For relatively simple applications where you're just performing CRUD operations, I would not bother with a DAL. In your controller, just query the data from the datacontext and populate ViewModels with it directly. The UI should not directly rely on the generated database classes - you should use ViewModels - but you don't really need a full DAL.

    If you are building a large-scale enterprise application, it may be different. For those I typically recommend a DAL to obscure the generated classes. The main reason is that it's easier to maintain in the long run. If you have 25 controllers and 200 middle-layer classes all depending on generated data classes, and 10 years from now someone decides to switch from EF to a different ORM, you'll be screwed. If you have a DAL long-term maintenance for that kind of thing is much easier.

    My rule to remember for architecture is that "proper" architecture is expensive. Go the agile route - if you need a DAL for long-term maintenance of a large-scale application, then write it. If you have a small application or it won't need to be maintained long-term, don't waste the time writing it. YAGNI.


    Check out My Blog. Now updated to actually work!

    Tuesday, February 7, 2012 4:39 PM
  • Tim,

    apologies that I used term aspx wrongly. You are right, now what I wanna know is that can I use above DAO/DAL that I wrote with controller to render the view?


    manoj.verma

    Thursday, February 9, 2012 8:15 AM
  • You can use anything you want to render the view.

    The normal practice is to create a ViewModel class, which contains all of the data needed to display/update a view. Then, write methods to populate that ViewModel class with your data - it doesn't matter where your data comes from (your DAL, or directly from the database).

    In your Get action, populate a ViewModel and pass it into your view. In your Post action, take that ViewModel, get the changed data out of it, and update your data. It doesn't matter how you update your data (through a DAL, web service calls, database updates, whatever you want).

    The views should be kept agnostic - they should only ever look at ViewModel objects. How you populate that ViewModel and what you do with the data in the post is entirely up to you. You can use whatever kind of data access strategy you can dream up.


    Check out My Blog. Now updated to actually work!

    Thursday, February 9, 2012 3:18 PM