[c#]是到动态切换数据库表在查询中可能吗?

标签: Asp.net Linq C#
发布时间: 2017/2/25 3:16:48
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

我相当新的 C# 编程。我有我需要读取数据动态地从数据库表,而我需要切换表取决于类别的情况。我从表中读取的数据始终是相同,只是表不同。 是到动态切换数据库表在查询中可能吗?

我做了一个抽象的代码来解释我的想法︰

                    var userPost = if(Category == "News"){ db.News } else { db.Sport}
                    .Include(x => x.Popular)
                    .Include(x => x.Popular.Category)
                    .Where(x => x.User.Id == userId)
                    .OrderByDescending(x => x.CreatedAt)
                    .ProjectTo<PostViewModel>(_mapper.ConfigurationProvider)
                    .ToPagedList(pageIndex, pageSize);

谢谢你;)

解决方法 1:

假设你的 ORM 将两个表映射到相同的类型,你应该能够做到这一点︰

var userPost = (Category == "News" ? db.News : db.Sport)
                .Include(x => x.Popular)
                .Include(x => x.Popular.Category)
                .Where(x => x.User.Id == userId)
                .OrderByDescending(x => x.CreatedAt)
                .ProjectTo<PostViewModel>(_mapper.ConfigurationProvider)
                .ToPagedList(pageIndex, pageSize);

或者,或许有点更具可读性︰

var table = (Category == "News" ? db.News : db.Sport);

var userPost = table
                .Include(x => x.Popular)
                .Include(x => x.Popular.Category)
                .Where(x => x.User.Id == userId)
                .OrderByDescending(x => x.CreatedAt)
                .ProjectTo<PostViewModel>(_mapper.ConfigurationProvider)
                .ToPagedList(pageIndex, pageSize);

如果你有你想要多路复用超过 2 表,你可能想要将出选择逻辑拆分为另一种方法︰

internal IQueryable<ROWTYPE> SelectTable(string category)
{
    switch (category)
    {
        case "News": return db.News;
        case "Sport": return db.Sport;
        case "Arts": return db.Arts;
        default: throw new ArgumentException("Unsupported category: " + category);
    }
} 



var table = SelectTable(Category);

var userPost = table
                .Include(x => x.Popular)
                .Include(x => x.Popular.Category)
                .Where(x => x.User.Id == userId)
                .OrderByDescending(x => x.CreatedAt)
                .ProjectTo<PostViewModel>(_mapper.ConfigurationProvider)
                .ToPagedList(pageIndex, pageSize);
官方微信
官方QQ群
31647020