[英]Dynamic query using linq
I have an Audit model that contains EntityName and EntityIds. 我有一个包含EntityName和EntityIds的审核模型。
I am looking for a way to create dynamic query that will retrieve the EntityRecord and related entities from this table 我正在寻找一种创建动态查询的方法,该方法将从该表中检索EntityRecord和相关实体
this is what I have so far 这就是我到目前为止
var auditRows = from a in context.Audit
where (a.EntityName == entityName && a.EntityKey == entityKey);
What I wanted to get is if an Entity, say "Class" has related entity "Students". 我想得到的是,如果一个实体(例如“ Class”)具有相关的实体“ Students”。 I want to craete a dynamic query that creates the where clause as 我想创建一个动态查询,将where子句创建为
where (a.EntityName == entityName && a.EntityKey == entityKey) ||
(a.EntityName == "Students" && context.Students.Where(s => s.ClassID == entityKey)
I found a way to get the related entities 我找到了一种获取相关实体的方法
var objectContext = ((IObjectContextAdapter)context).ObjectContext;
var container = objectContext.MetadataWorkspace.GetEntityContainer(objectContext.DefaultContainerName, DataSpace.CSpace);
var relatedEntitySets = container.EntitySets.Where(es => es.ElementType.Name == entitySet).First().ElementType.NavigationProperties
but I don't know how to build the query or if there is a better way to create the query. 但我不知道如何构建查询或是否有更好的方法来创建查询。
I think you just need to get rid of the WHERE and replace with ANY: 我认为您只需要摆脱WHERE并替换为ANY:
var students = context.GetTable<Students>();
// Repeat for other tables
where (a.EntityName == entityName && a.EntityKey == entityKey) ||
(a.EntityName == "Students" && students.Any(s => s.ClassID == entityKey) ||
(a.EntityName == "People" && people.Any(s => s.ClassID == entityKey) ||
(a.EntityName == "FOO" && foo.Any(s => s.Bar == entityKey)
Any will generate the WHERE EXISTS() you want. 任何都将生成所需的WHERE EXISTS()。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.