SventoryMang
SventoryMang

Reputation: 10478

Entity Framework: Generic compare type without Id?

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?

Upvotes: 1

Views: 786

Answers (1)

Eranga
Eranga

Reputation: 32447

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;
}

Upvotes: 1

Related Questions