简体   繁体   中英

Dynamically query entity framework with linq

I need a function to get a key-value pair of Id and Description from a entity model for populating some fields on a user control and I'd like to find a way to make it dynamic in order to avoid repeating code.

My pseudo-code:

public List<object> GetData(string modelName, string modelId, string modelDescription)
{
    using(DbEntities context = new DbEntities())
    {
        return (from d in context.modelName
                select new { 
                            id=d.modelId,
                            description = d.modelDescription
                           }
               ).ToList<object>();
    }
}

A possible partial solution could be this , but the table needs to be dynamically defined too.

In you context you have something similar to

public DbSet<MyEntity> ThePropertyName {get; set;}

when you call you function modelName = "ThePropertyName"

So you could retrieve the DbSet via reflection then run a ToList on it. Then you could use a foreach on the entities and via reflection you could retrieve the properties modelId and modelDescription.

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