首页 > 解决方案 > 如何将“FromSql()”查询的结果建模为基本数据类型?

问题描述

我正在使用 EF Core 3.1 中的无键实体类型功能。我想将一些表数据映射到我的实体类中。这是我的db-context配置:

    public class HimartWarehouseReportContext: DbContext
{
    public HimartWarehouseReportContext()
    {
    }

    public HimartWarehouseReportContext(DbContextOptions<HimartWarehouseReportContext> options)
        : base(options)
    {
    }

    public DbSet<MarketPresence> MarketPresence { get; set; }
    public DbSet<Campaign> Campaign { get; set; }
    public DbSet<CampaignDt> CampaignDt { get; set; }
    public DbSet<List<String>> Category { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.Entity<MarketPresence>().HasNoKey().ToView(null);
        modelBuilder.Entity<Campaign>().HasNoKey().ToView(null);
        modelBuilder.Entity<List<String>>().HasNoKey().ToView(null);
    }
}

关于我MarketPresenceCampaign班级,当我像这样使用它们时一切正常:

public IEnumerable<Campaign> GetCampaignReports(Campaign input)
{
   var result = _reportContext
                .Campaign
                .FromSqlRaw("GetCampaignReport " + 
                            $"{input.ProvinceId}, " +
                            $"{input.CityId}")
}

但关于最后一种情况Category,我只想返回字符串列表作为我的 sql 查询的结果,我收到这条消息的异常:(The required column 'Capacity' was not present in the results of a 'FromSql' operation.容量是我的 sql 结果查询的名称,查询的结果是一个表列名为容量)我怎么能想出这个问题?

感谢您的关注。

标签: entity-framework-core

解决方案


我有类似的东西,只是做了一个像你的 Category 类的类,它有数百个属性。这是我能想到的最简单的方法。


推荐阅读