【问题标题】:Entity Framework Core DBContext Datamodel as variable实体框架核心 DBContext 数据模型作为变量
【发布时间】:2018-06-07 16:03:34
【问题描述】:

我正在尝试使用 Entity Framework Core 在 ASP.NET Core 2 中创建具有 REST API 服务的通用列表提要。我想引入一个字符串,该字符串将确定用于提要的表。我在初始化通用 DBContext.DataModel 变量时遇到问题,我可以稍后将我的 _context.Model 分配给我的 linq 命令。这将由我的控制器调用。

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;
}

【问题讨论】:

    标签: c# asp.net-core-2.0 dbcontext entity-framework-core-2.1


    【解决方案1】:

    如果上下文有一组表,每个表都用于实现相同基类的对象类型,您可以使用.Cast&lt;T&gt;() 扩展。

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

    【讨论】:

    • 这不起作用,因为当我执行 var data = await feed.Where(f => f.Inactive == false).ToListAync 的 LINQ 命令时,我无法调用下面的 context.model 对象();我需要初始化对象类型,以便稍后在代码中的 EF 调用中使用它。
    • 只要在这点之前的所有代码路径都初始化了值。编译器会好的。否则:IEmumerable&lt;GenericFeedResource&gt; feed = new List&lt;GenericFeedResource&gt;(); 将起作用。
    • 实际上 feed 应该是单个对象而不是对象数组。下面的数据变量将是数组。
    • 好的。我现在已完成编辑您的答案,这在我的代码中有效。不过让我走上了正轨。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-22
    • 1970-01-01
    • 2020-05-16
    • 2020-10-15
    • 2016-11-08
    • 2017-10-01
    相关资源
    最近更新 更多