Wednesday, May 25, 2011

Code-First Development with Entity Framework 4.1

Entity Framework 4.1 is delivered with MVC 3 (Tools Update). It allows for easier Code-First Development, which means creating custom busines objects/entities and repositories (data context), and then mapping them to the database. Rather than the other way around, which is usually the case (unless you use NHibernate and have known about this for years :).

One issue that I ran into when using Code First Development was that I tried to add my own objects to the project that already had an .edmx model generated from the database. For some reason EF goes nuts and things just don't work.

The solution to that is to remove .edmx in some way. Either rewrite the objects to use Code First or separate them into separate assemblies.

For more info, see

All the code that needs to be written is the Model. I use the following classes as a start:


public class WorkItem
        public int Id { getset; }
        public string ItemName { getset; }
        public int WorkOrderId { getset; }

        public virtual WorkOrder Order { getset; }
    public class WorkOrder
        public int Id { getset; }
        public string Title { getset; }
        public DateTime? OrderDate { getset; }

        public virtual ICollection<WorkItem> Items { getset; }


No comments: