实体框架:没有Id的通用比较类型? [英] Entity Framework: Generic compare type without Id?

查看:93
本文介绍了实体框架:没有Id的通用比较类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在对象之间进行比较是否总体上没有对象具有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);
    }
}

或类似的东西。我的系统的问题是不是每个类都有一个名为Id的属性,具体取决于类可以是ClassnameId。那么我还有什么要通过LINQ检查存在并返回这样一个实体,而不是一般地提供任何属性?

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?

推荐答案

尝试

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

这篇关于实体框架:没有Id的通用比较类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆