Lambda表达式作为动态调度操作的参数 [英] Lambda expression as an argument to a dynamically dispatched operation

查看:83
本文介绍了Lambda表达式作为动态调度操作的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

被错误卡住:

Cannot use a lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type

对于一个简单的示例,让我们尝试使用实体框架从数据库中获取对象,而实际上不知道其类型:

For a simple example, let's try to get an object from database using entity framework without actually knowing its type:

private DbContext db;
private dynamic test(dynamic entity)
{
    return db.Set(entity.GetType()).First(x => x.Id == entity.Id);
}

我该如何进行这项工作?

How can I make this work?

推荐答案

使用泛型而不是dynamic:

private DbContext db;
private T test<T>(T entity)
    where T : BaseEntity
{
    return db.Set<T>().First(x => x.Id == entity.Id);
}

具有一个具有Id属性的BaseEntity,以确保给定的实体具有ID.

Have a BaseEntity that has an Id property, to ensure that the given entity has an Id.

这篇关于Lambda表达式作为动态调度操作的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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