I like Entity Framework (EF), I think it is a little too rigid sometimes and it would be very nice if there was a very straight forward way to get Plain Old CLR Objects (POCO) out of EF Entities. One can dream, can he not?! Going on a tangent, there are ways to get POCO out of EF Entities, but I haven’t gotten them to work yet, I have looked through many tutorials and wasted a full work day trying to find a way around it. That being said, beware if you plan on using EF with WCF, some of your more complicated EF Entities will not go over the pipe in WCF. The reason simply being that there are un-serializable properties in those Entities. Hence the need for POCO.
I would really have liked EF to just have very simplistic syntax for the most basic of operations, those being CRUD operations. Since that is not the case, I am going to just put it here on my blog because I don’t think I should have to ever look this stuff up again (I’ve done this too many times already).
I am going to use everyone’s favorite used to death example, yes you guessed it – the Product object.
Read Operations
//Your basic Getter - the "R" of CRUD public static Product GetProduct(int productID) { using (DBEntities context = new DBEntities()) { //Using Linq or Lamba get your product. return context.ProductEFs.Where(p => p.ProductID == productID).FirstOrDefault(); } } //Your basic Get All - also the "R" of CRUD public static List<Product> GetProducts() { using (DBEntities context = new DBEntities()) { return context.ProductEFs.ToList(); } }
Write Operations
//Your rudimentary Crud Operations, this is only the "C", "U" & "D" of CRUD public enum CrudOperations { Insert = 1, //Create Update = 2, //Update Delete = 3 //Delete } //This is the remaining "C", "U" & "D" of CRUD. //This method takes a product object and a CRUD Operation public void Operation(Product product, CrudOperations op) { try { using (DBEntities context = new DBEntities()) { switch (op) { case CrudOperations.Insert: context.AddToProductEFs(product); //The most straight forward operation, add to the collection break; case CrudOperations.Update: context.ProductEFs.Attach(product); //Must attach first and change the state to modified context.ObjectStateManager.ChangeObjectState(product, EntityState.Modified); break; case CrudOperations.Delete: context.ProductEFs.Attach(product); //Must attach first context.DeleteObject(product); //Then you can perform a delete break; } //All of these operations have this in common context.SaveChanges(); } } catch (Exception ex) { //Log this error if you choose to. //Return something less frightening - PO = Product Operation throw new Exception("PO:" + op.ToString() + " - " + ex.Message); } }
Not terribly complicated once you have the code in front of you, but it isn’t obvious when starting from scratch. I am debating on making extension methods for all of this so it will simply read: context.Insert(), context.Update(), context.Delete() etc..