Entity Framework Generic Repository

后端 未结 2 1456
猫巷女王i
猫巷女王i 2021-01-03 11:42

I am writing a generic repository to be used for my every model CRUD operation using entity framework CTP5 as following:

  public class BaseRepository

        
相关标签:
2条回答
  • 2021-01-03 12:33

    You're overwriting the variable status with a totally new object, taking the one from the database out of scope, but not actually modifying the object that is attached to the context, which is what you'll want to do.

    The only way I can think off the top of my head is to use reflection to read all the properties of the type, and assign the values to the original object based on the new one, something like:

    foreach (var prop in typeof(TEntity).GetProperties())
    {
        prop.SetValue(status, prop.GetValue(entity, null), null);
    }
    
    0 讨论(0)
  • 2021-01-03 12:38

    You can use CurrentValues.SetValues:

    public void Update(TEntity entity)
    {
        TEntity status = Context.Set<TEntity>().Find(entity.Id);
        Context.Entry(status).CurrentValues.SetValues(entity);
        Context.SaveChanges();
    }
    

    It updates scalar and complex properties but not navigation properties.

    0 讨论(0)
提交回复
热议问题