Search code examples
entity-frameworkentitypocoobjectcontext

Entity Framework POCO Update Entity?


I am trying to so something really, really simple, but Entity Framework seems to have dozens of ways of doing it none of which seem to work.

I have a POCO class that I have read from a database, and I want to update the database with changes to that class. That is all I want to do.

Here is what I am trying:-

1) My POCO class:-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Web.Mvc; // Needs project reference to System.Web.Mvc 3.0.0.0
using System.ComponentModel.DataAnnotations; // Needs project reference to System.ComponentModel.DataAnnotations 4.0.0.0

namespace Trust.Domain.Entities
{
    public class Product
    {
        [HiddenInput(DisplayValue=false)]
        public Int32 ProductID { get; set; }
        [Required(ErrorMessage = "Please enter a product name.")]
        public String Name { get; set; }
        [DataType(DataType.MultilineText)]
        public String Description { get; set; }
        public Decimal? PriceGuide { get; set; }
        public Decimal? PriceSold { get; set; }
        public Int32? HeightCM { get; set; }
        public Int32? WidthCM { get; set; }
        public Int32? DepthCM { get; set; }
        [Required(ErrorMessage = "Please enter a list of keywords. Seperate each with a comma.")]
        public String Keywords { get; set; }
        public String SKU { get; set; }
        public Int32 ProductStateID { get; set; }
    }
}

2) My context for updating an instance of this POCO class:-

using System; using System.Collections.Generic; using System.Linq;
using System.Text;

using Trust.Domain.Entities; using Trust.Domain.Abstract;

namespace Trust.Domain.Contrete {
    public class EFProductRepository : IProductRepository
    {
        private EFDbContext context = new EFDbContext();

        public IQueryable<Product> Products
        {
            get { return context.Products; }
        }

        public Product GetProduct(int productID)
        {
            Product product = context.Products.Where(p => p.ProductID == productID).FirstOrDefault();
            return product;
        }

        public void SaveProduct(Product product)
        {
            if (product.ProductID == 0)
            {
                context.Products.Add(product);
                context.SaveChanges();
            }
            else
            {
                //context.AttachTo("Product", product); 
                //var contactEntry = Context.ObjectStateManager.GetObjectStateEntry(product); 
                //contactEntry.ChangeState(EntityState.Modified); 
                //_context.SaveChanges();

                //var findProduct = GetProduct(product.ProductID); 
                //context.ApplyCurrentValues("Product", product); 
                //context.SaveChanges(); 

                context.Products.Attach(product);
                context.SaveChanges();

            }
        }

        public void DeleteProduct(Product product)
        {
            context.Products.Remove(product);
            context.SaveChanges();
        }
    }
}

3) EFDbContext is defined as:-

using System; using System.Collections.Generic; using System.Linq;
using System.Text;

using System.Data.Entity; // Needs Entity Framework 4.1 project
reference. using System.Data.Entity.ModelConfiguration.Conventions;

using Trust.Domain.Entities;

namespace Trust.Domain.Contrete {
    public class EFDbContext : DbContext
    {
        #region " Overrides "

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();

            base.OnModelCreating(modelBuilder);
        }

        #endregion

        #region " Entities "

        public DbSet<Product> Products { get; set; }

        #endregion
    }
}

In the SaveProduct routine I check whether the ProductID is not zero. If it is not zero then I try to update the entity in the database. In this code I present three ways of doing this that I have found around and about. The first two are comment out because they do not even compile because the members that they use don't exist! The third looks good, runs and makes no change the database at all.

Entity Framework is a vary large, complex and over engineered technology and so there are loads of ways to do anything. Can someone please tell me how to update my Product entities given the POCO type and the EFDbContext based context that I have created. What I am trying to do should be stunningly simple, I don't know why it is not.


Solution

  • The reason why those members don't exists is that there are two different APIs for EF: older ObjectContext API and newer DbContext API. Those first two solutions are using ObjectContext API but you are using DbContext API.

    The problem is that attaching entity will only attach it but it will mark it as unchanged so you need to mark it as modified so that EF knows that entity has to be saved:

    context.Products.Attach(product);
    context.Entry(product).State = EntityState.Modified;
    context.SaveChanges();
    

    The first line is mostly unneeded because the second will attach the entity anyway if you set its state to modified but I like to keep it in the code to make this obvious.