剑轩

ef core检查某个字段是否是主键,ef不查询更新

电脑版发表于:2020/2/28 11:40

使用反射检查ef中某个字段是否是主键,使用如下代码即可

//检测当前字段是否是主键
var keys = userm.Property(item.Name).Metadata.GetType().GetProperty("Keys");
object value = keys.GetValue(userm.Property(item.Name).Metadata);

可以用于在封装不需要查询直接更新的时候用,因为如果是主键设置IsModified=true就会报错

完整一点的代码:

public int Update<T>(T t) where T : class
    {
        var userm = efcontext.Entry<T>(t);
        //把user对象加入上下文,但是没有改变
        userm.State = Microsoft.EntityFrameworkCore.EntityState.Unchanged;
        //使用反射找到不为空的字段
        foreach (var item in t.GetType().GetProperties())
        {
            //虚拟属性是导航属性
            if (item.GetMethod.IsVirtual)
            {
                continue;
            }
            //拿到属性值
            object obj = item.GetValue(t);
            if (obj != null)
            {
                //检测当前字段是否是主键
                var keys = userm.Property(item.Name).Metadata.GetType().GetProperty("Keys");
                object value = keys.GetValue(userm.Property(item.Name).Metadata);
                //不是主键才去修改,如果是主键就不需要修改了
                if (value == null)
                {
                    //表示该字段需要更新
                    userm.Property(item.Name).IsModified = true;
                }
            }
        }
        return efcontext.SaveChanges();
    }

其实可以多传递一个忽略的字段比如主键,不然的话,每次去反射检查很浪费效率的还不如重新查询一次了

public int Update<T>(T t, string keyName) where T : class
{
    var userm = efcontext.Entry<T>(t);
    //把user对象加入上下文,但是没有改变
    userm.State = Microsoft.EntityFrameworkCore.EntityState.Unchanged;
    //使用反射找到不为空的字段
    foreach (var item in t.GetType().GetProperties())
    {
        //虚拟属性是导航属性
        if (item.GetMethod.IsVirtual)
        {
            continue;
        }
        //拿到属性值
        object obj = item.GetValue(t);
        if (obj != null)
        {
            //不是主键才去修改,如果是主键就不需要修改了
            if (item.Name != keyName)
            {
                //表示该字段需要更新
                userm.Property(item.Name).IsModified = true;
            }
        }
    }
    return efcontext.SaveChanges();
}

使用的时候这样既可:

public int UpdateAtricle(Article article)
{
    return _efHelper.Update(article, "Id");
}



关于TNBLOG
TNBLOG,技术分享。技术交流:群号677373950
ICP备案 :渝ICP备18016597号-1
App store Android
精彩评论
{{item.replyName}}
{{item.content}}
{{item.time}}
{{subpj.replyName}}
@{{subpj.beReplyName}}{{subpj.content}}
{{subpj.time}}
猜你喜欢