Ewerton
Ewerton

Reputation: 4533

Generic Repository with EF 5.0 is not working

I have a generic repository for my Entities, all my entities (generated by the Code generation Item) have a personalized partial that implements an IID interface, at this point all of my entites must have a Int32 Id property.

So, my problems is with the update, here is my code

public class RepositorioPersistencia<T> where T : class
{
    public static bool Update(T entity)
    {
        try
        {
            using (var ctx = new FisioKinectEntities())
            {
                // here a get the Entity from the actual context 
                var currentEntity = ctx.Set<T>().Find(((BLL.Interfaces.IID)entity).Id);

                var propertiesFromNewEntity = entity.GetType().GetProperties();
                var propertiesFromCurrentEntity = currentEntity.GetType().GetProperties();

                for (int i = 0; i < propertiesFromCurrentEntity.Length; i++)
                {
                    //I'am trying to update my current entity with the values of the new entity
                    //but this code causes an exception
                    propertiesFromCurrentEntity[i].SetValue(currentEntity, propertiesFromNewEntity[i].GetValue(entity, null), null);
                }
                ctx.SaveChanges();
                return true;
            }

        }
        catch
        {

            return false;
        }
    }
 }

Someone can help me? this driving me crazy.

Upvotes: 3

Views: 1172

Answers (1)

Eranga
Eranga

Reputation: 32447

You can use the EF API to update the values of an entity as follows.

public static bool Update(T entity)
{
    try
    {
        using (var ctx = new FisioKinectEntities())
        {
            var currentEntity = ctx.Set<T>().Find(((BLL.Interfaces.IID)entity).Id);

            var entry = ctx.Entry(currentEntity);
            entry.CurrentValues.SetValues(entity);

            ctx.SaveChanges();
            return true;
        }
    }
    catch
    {

        return false;
    }
}

Upvotes: 2

Related Questions