Saturday, March 16, 2013

Add, Update with Entity Framework 5

CRUD sample with Entity Framework 5.

in EF 5 there is something called DBContext, which is little different than earlier ObjectContext, DBContext generate less code to achieve the same functionality, and is based on code first principle

this is how the dbcontext file look like and connection string to be set

public partial class GoldEntities : DbContext
    {
        static string secureConnectionString = Util.EntityFrameworkConnectionString;

        public GoldEntities()
            : base(secureConnectionString)
        {
        }
}


ADD :

public bool AddDesignType(tbProductType designType)
        {
            bool result = false;
            using (var context = new GoldEntities())
            {
                context.tbProductTypes.Add(designType);
                context.SaveChanges();
                result = true;
            }
            return result;
        }

UPDATE using Entityframework 5:
to update an entity you wont find applychanges method, so here is how you can update an entity.

public bool UpdateColorStoneName(tbColorStoneName colorStoneName)
        {
            bool isSaved = false;
            using (var context = new GoldEntities())
            {
                tbColorStoneName csn = context.tbColorStoneNames
                    .Where(d => d.ColorStoneNameId == colorStoneName.ColorStoneNameId)
                    .FirstOrDefault();

                if (csn != null)
                {
                    context.Entry(csn).State = EntityState.Modified;
                    context.SaveChanges();
                    isSaved = true;
                }
            }
            return isSaved;
        }




No comments:

ETG Consultancy

Web Designing Development Analysis & Promotion
Asp.Net 2.0 SQL WWF WCF SEO Marketing Ajax JQuery NHibernate MVC