如何从ExecuteSqlInterpolatedAsync获取查询结果?

时间:2019-11-19 09:34:07

标签: entity-framework-core-3.0

Entity Framework Core 3.0引入了一种新方法ExecuteSqlInterpolatedAsync,如此处所述:

RelationalDatabaseFacadeExtensions.ExecuteSqlInterpolatedAsync()

示例查询是这样的:

context.Database.ExecuteSqlInterpolatedAsync($"SELECT * FROM [dbo].[SearchBlogs]({userSuppliedSearchTerm})");

如何获取此查询返回的结果?甚至有可能吗?

2 个答案:

答案 0 :(得分:1)

ExecuteSqlInterpolatedAsync返回作为任务结果受影响的行数。使用FromSqlInterpolated获得结果-有关用法示例,请参见this issue

答案 1 :(得分:0)

如果您要更新数据库中的记录,则将使用ExecuteSqlInterpolatedAsync并返回一个整数,该整数指示受更改影响的记录总数,并且如果在数据库中还具有用于更新或删除或创建记录的存储过程,您可以使用ExecuteSqlInterpolatedAsync例如; var受影响的行=等待context.Database.ExecuteSqlInterpolatedAsync($“ Exec CustomerUpdate {id}”); 其中id是此上下文中的预期存储过程参数。 但是对于你的问题, 您需要执行以下操作; 1.创建名为HeadCash的类,

  [Keyless]
   public class HeadCash
   {
         public string EmployeeID { get; set; }
   }

2。将类作为DbSet添加到DBContext中,例如;

     public virtual DbSet<HeadCash> HeadCash { get; set; }
  1. 创建方法以生成所需的数据,例如在执行类中;

    public async Task<IEnumerable<HeadCash>> CheckHeadCash(string Id)
    {
        try
        {
            var headcash =await _context.HeadCash.FromSqlInterpolated($"EXEC 
              GetHeadCash {Id}").ToListAsync();
    
            return headcash;
        }
        catch (Exception)
        {
    
            throw;
        }
    }
    

    请注意,请记住像上面的步骤1一样在类上添加[KeyLess]属性。