简体   繁体   中英

Entity Framework Core DBContext Datamodel as variable

I am trying to create a generic list feed with a REST API service in ASP.NET Core 2 using Entity Framework Core. I want to bring in a string that will determine what table is used for the feed. I am having trouble initializing a generic DBContext.DataModel variable that I can assign my _context.Model to for my linq command later. This will be called by my controller.

public class ServiceRepository : IServiceRepository

    private readonly MyDataDbContext _context

    public ServiceRepository(MyDataDbContext context){
        _context = context;
    }
    public async Task<IEmumerable<GenericFeedResource>> GetFeed(string feedType){
        var feed = new ???  (What object to use?)

        switch(feedType)
            {
            case: "Feed1": feed = _context.Model1;
                break;
            ...
            }

        var data = await feed.Where(f => f.Inactive == false).ToListAync();

        ... var result = formatting of data

        return result;
}

If the context has a set of tables that are each for object types that implement the same base class you can use the .Cast<T>() extension.

IEmumerable<GenericFeedResource> feed;

switch(feedType)
{
    case: "Feed1": 
        feed = _context.Model1.Cast<GenericFeedResource>();
        break;
}

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