Entity Framework: generic comparison type without Id?

Is it even necessary to compare objects for equality without objects with an identifier?

I am trying to make a typical general update, for which I have seen many examples online, but all of them 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 an Id property, depending on the class Id there may be a ClassnameId. Anyway, should I check for the presence and return of such an object via LINQ without providing any properties in general?

+1
source share
1 answer

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; } 
+1
source

Source: https://habr.com/ru/post/1392721/


All Articles