简体   繁体   中英

Dynamic query using linq

I have an Audit model that contains EntityName and EntityIds.

I am looking for a way to create dynamic query that will retrieve the EntityRecord and related entities from this table

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". I want to craete a dynamic query that creates the where clause as

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM