繁体   English   中英

如何从实体框架动态获取 select 表?

[英]How to select table dynamically from Entity Framework?

我在 c# 中有这个 function:

using (SKContext db = new SKContext())
{
    dynamic dynamic = new ExpandoObject();

    if (category == "Categories")
    {
        dynamic = db.Categories
                    .Where(X => X.Active == true)
                    .Select(f => f.Name).ToList();
    }
    else if (category == "Brands")
    {
        dynamic = db.Brands
                    .Where(X => X.Active == true)
                    .Select(f => f.Name).ToList();
    }
    else if (category == "Characters")
    {
        dynamic = db.Characters
                    .Where(X => X.Active == true)
                    .Select(f => f.Name).ToList();
    }

    return dynamic;
}

我想通过字符串动态选择一个表,如下所示:

var tableName = "Brands";
return db.[tableName].Where(X => X.Active == true).Select(f => f.Name).ToList();

任何人都可以帮忙吗?

我建议不要使用动态,而是引入一些鉴别器类型/接口并在那里声明通用属性/功能:

public interface ISomeInterface
{
    bool Active { get; set; }
    string Name { get; set; }
}

public class Category : ISomeInterface {...} // and others

并使用此接口构建查询:

IQueryable<ISomeInterface> query = category switch
    {
        "Categories" => db.Categories,
         // ...
        _ => throw new ArgumentOutOfRangeException()
    };
 return query.Where(X => X.Active == true).Select(f => f.Name).ToList();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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