使用 lambda 表达式进行反射

发布于 2024-12-16 12:59:20 字数 610 浏览 1 评论 0原文

我想传入一个方法三个参数。类名(表)、字段和关键字。

然后我想使用带有反射的实体框架来获取表并找到具有关键字的字段。

但是

public List<object> FilterOptions(string keyword, string className, string field)
        {
            var objectSet = (System.Data.Objects.ObjectSet<dynamic>)DataContext.GetType().GetProperty(className).GetValue(DataContext, null);
            var options = objectSet.Where(x => x.GetType().GetProperty(field).GetValue(x, null) == keyword).ToList();
...
        }

我得到“表达式树可能不包含动态操作”,

当我将 更改为 时,我再次收到错误。

I want to pass in a method three parameters. The Classname (table), the field and the keyword.

Then I would like to take with Entity Framework with reflection the table and find the fields that have the keyword.

Something like

public List<object> FilterOptions(string keyword, string className, string field)
        {
            var objectSet = (System.Data.Objects.ObjectSet<dynamic>)DataContext.GetType().GetProperty(className).GetValue(DataContext, null);
            var options = objectSet.Where(x => x.GetType().GetProperty(field).GetValue(x, null) == keyword).ToList();
...
        }

However I get "An expression tree may not contain a dynamic operation"

When I change <dynamic> to <object> I get an error again.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

握住我的手 2024-12-23 12:59:21

我想这就是你想要结束的地方。您想要实体的字段名称吗?

ObjectContext 类上有一个名为 MetadataWorkspace 的属性。您可以深入到具有名为 MetadataProperties 的属性的 EntitySet。像这样的东西。

public List<object> FilterOptions(string keyword, string className, string field)
{
    return ObjectContext.MetadataWorkspace.GetEntityContainer(context.DefaultContainerName, DataSpace.CSpace).BaseEntitySets.Where(es => es.MetadataProperties.Any(mp => mp.Name == keywork));
    // This has not been tested but should get you on the right path.
}

请参阅此链接

希望这有帮助。

PS 我还建议接受您的更多答案。你的接受率只有 33%。这意味着你的问题最终会被忽略。请记住,如果您在其他地方找到了答案,您可以回答自己的问题。 :0)

I think this is where you want to end up. You are wanting field names for your entities?

there is a property on the ObjectContext class called MetadataWorkspace. You can drill down to an EntitySet which has a property call MetadataProperties. Something like this.

public List<object> FilterOptions(string keyword, string className, string field)
{
    return ObjectContext.MetadataWorkspace.GetEntityContainer(context.DefaultContainerName, DataSpace.CSpace).BaseEntitySets.Where(es => es.MetadataProperties.Any(mp => mp.Name == keywork));
    // This has not been tested but should get you on the right path.
}

see this link.

Hope this helps.

P.S. I also would recommend accepting more of your answers. You only have a 33% accept rate. Which means your question will eventually just get passed by. Remember if you found the answer somewhere else you can answer your own question. :0)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文