1

Is there anyway to do a comparison between objects for equality generically without objects having an ID?

I am trying to do a typical generic update, for which I have seen many examples of online, but they all usually look something like this:

public void Update(TClass entity)
{
    TClass oldEntity = _context.Set<TClass>().Find(entity.Id);
    foreach (var prop in typeof(TClass).GetProperties())
    {
        prop.SetValue(oldEntity, prop.GetValue(entity, null), null);
    }
}

or something similar.The problem with my system is that not every class has a property named Id, depending on the class the Id can be ClassnameId. So is there anyway for me to check for the existence of and return such an entity via LINQ without supplying any properties generically?

SventoryMang
  • 10,275
  • 15
  • 70
  • 113

1 Answers1

1

Try

public void Update(TClass entity)
{
    var oldEntry = _context.Entry<TClass>(oldEntity);

    if (oldEntry.State == EntityState.Detached)
    {
         _context.Set<TClass>().Attach(oldEntity);
    }

    oldEntry.CurrentValues.SetValues(entity);
    oldEntry.State = EntityState.Modified;
}
Eranga
  • 32,181
  • 5
  • 97
  • 96
  • Thannks, from what I read though update values only updates complex and scalar properties but not navigation properties? So does this mean if I have a user which has a collection of Groups and remove one group and update, that change won't apply with CurrentValues.SetValues? Or does it simply mean I can't change and update the actual group object via this method on the user object? http://stackoverflow.com/questions/6974660/entity-framework-generic-repository. Also are there typos in your code? Seems like Entry should take entity as parameter, and is it detached if I just got it from db? – SventoryMang Jan 23 '12 at 15:27
  • @DOTang you are correct about the navigational properties. A generic update method will not work for all cases. I didn't compile the above code. So there maybe typos – Eranga Jan 23 '12 at 16:17
  • @Erange Thanks Eranga, but can you please clarify what that means, If I have a User object with a ICollection of Groups. Does it mean that a) if I remove groups from that collection of a specific user and update the user, the removed groups changes won't be saved, or b) it means if I try to change the actual group object (say I change the name property) from the collection, and update the user, the group object changes won't be saved? – SventoryMang Jan 23 '12 at 16:57
  • ...typoed your name in previous comment. – SventoryMang Jan 23 '12 at 17:17