如何根据LINQ和实体框架的条件进行项目属性?
我想为 LINQ List 声明类属性的变量。 我在数据库中有大约 100 个属性,我想根据用户选择更改输出数据。例如,如果用户选择“A”,我想从 EntityFramework 获取“A”值。
这是我的示例代码:
List<ReadTime> report = bWDiagnosticEntities2.CA190STEST
.Where(x => (x.Date > StartDate) && (x.Date <= EndDate))
.Select(x => new ReadTime
{
Date = x.Date,
kody5 = x.kodyBledow5NetVarA
})
.OrderBy(x => x.Date)
.ToList();
我想更改为:
kody5 = x.kodyBledow5NetVarA
其中
kody5 = myVariable
myVariable 取决于用户发送的模型。
I would like to declare variable of class property for LINQ List.
I have about 100 properties in Database and i would like to change output data depends on user choice. For example if user chose "A" i would like to get "A" values from EntityFramework.
Here is my sample code:
List<ReadTime> report = bWDiagnosticEntities2.CA190STEST
.Where(x => (x.Date > StartDate) && (x.Date <= EndDate))
.Select(x => new ReadTime
{
Date = x.Date,
kody5 = x.kodyBledow5NetVarA
})
.OrderBy(x => x.Date)
.ToList();
I would like to change:
kody5 = x.kodyBledow5NetVarA
to
kody5 = myVariable
Where myVariable depends on model sent from User.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为最简单的方法是将查询和投影零件分开。
查询将由EF在数据库端运行,并检索所有字段。
然后,您进行内存中的投影,并根据用户的选择注入属性(用户必须从列表中选择现有属性)。
在EF查询中要记住的一件重要的事情是,当您调用
tolist()
时,您将执行实际的数据库查询。然后,所有其他语句将在内存中执行。如果数据卷是一个问题(并且可能会因为您告诉您有一百个字段),请在
tolist()
之前执行第一个select()
,其中无论如何,您都将严格地投射所需的字段。I think the simplest approach would be to split your query and projection parts.
Query will be run by EF on database side, and retrieve all the fields.
Then you do your projection in-memory, and inject the property based on user's choice (the user is required to pick an existing property from a list).
One important thing to remember in an EF query, is that when you call
ToList()
, you will perform the actual database query. Then all the further statements will be performed in memory.If the data volume is an issue (and it might, since you told you have like a hundred fields), perform a first
Select()
before theToList()
, where you will project strictly just the fields you will need, in any case.