[英]Order by child records using dynamic field with entity framework
I am interested in sorting a query using entity framework and am having trouble sorting using a dynamic order by expression, 我对使用实体框架对查询进行排序感兴趣,并且在通过表达式使用动态顺序进行排序时遇到了麻烦,
I have a parent record (DatasetRecord) with a one to many relationship consisting of a number of associated values (DatasetValues), I would like to be able to sort based on the data stored within the value if it matches a certain field, 我有一个父记录(DatasetRecord),它具有一对多的关系,并由多个关联值(DatasetValues)组成,如果它匹配某个字段,我希望能够根据存储在该值中的数据进行排序,
So I need to sort by the Value of DatasetValues where it matches a supplied FieldID 因此,我需要按与提供的FieldID匹配的DatasetValues的值进行排序
public IEnumerable<DatasetRecordDto> FetchData(ModuleSettingsDto settings)
{
var query = _context.DatasetRecords.AsQueryable().Where(r => r.DatasetId == settings.DatasetId && r.IsDeleted == false);
foreach (var filter in settings.Filters)
{
// this works fine, check we have current field and value matches
query = query.Where(i => i.DatasetValues.Any(x => x.DatasetFieldId == filter.DatasetFieldId && x.Value == filter.Value));
}
foreach (var sort in settings.Sort)
{
switch (sort.SortDirection)
{
case "asc":
// THIS IS WHERE I NEED THE DYNAMIC ORDER BY EXPRESSION,
// THIS SHOULD SORT BY DATETIME WHERE FIELD ID MATCHES
query = query.OrderBy(i => i.DatasetValues.Any(x => x.ValueDateTime && x.DatasetFieldId == sort.DatasetFieldId));
break;
}
}
return ShapeResults(query);
}
And here is my database schema: 这是我的数据库架构:
CREATE TABLE [dbo].[DatasetRecords](
[Id] [int] IDENTITY(1,1) NOT NULL,
[DatasetId] [int] NOT NULL
)
CREATE TABLE [dbo].[DatasetFields](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Label] [varchar](50) NOT NULL,
[DatasetId] [int] NULL,
[DataType] [int] NOT NULL
)
CREATE TABLE [dbo].[DatasetValues](
[Id] [int] IDENTITY(1,1) NOT NULL,
[DatasetRecordId] [int] NOT NULL,
[DatasetFieldId] [int] NOT NULL,
[ValueString] [varchar](8000) NULL,
[ValueInt] [int] NULL,
[ValueDateTime] [datetime] NULL,
[ValueDecimal] [decimal](18, 2) NULL,
[ValueBit] [bit] NULL
)
Please let me know if you need any further info, any help is greatly appreciated, 如果您需要更多信息,请告诉我,我们将不胜感激,
UPDATE: I am not having an issue with creating a dynamic order by expression, I am trying to apply a conditional sort order for parent records based on the values in a child table 更新:我没有通过表达式创建动态顺序的问题,我正在尝试根据子表中的值对父记录应用条件排序顺序
Have you tried running the Linq code on something like LinqPad, it lets you run Linq code against a dataset and shows you the generated SQL. 您是否尝试过在LinqPad之类的文件上运行Linq代码,它使您可以对数据集运行Linq代码并向您显示生成的SQL。 You can take that SQL and run it manually to make sure it isn't some invalid SQL that is causing the error.
您可以使用该SQL并手动运行它,以确保不是导致该错误的某些无效SQL。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.