我对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);
谢谢;)
答案 0 :(得分:2)
假设您的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);
如果要复用多个表,则可能需要将选择逻辑拆分为另一种方法:
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);