Entity Framework: Generic compare type without Id?

早过忘川 提交于 2020-01-05 04:27:07

问题


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?


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


来源:https://stackoverflow.com/questions/8948815/entity-framework-generic-compare-type-without-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!