You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET Core MVC中Context.Database.ExecuteSqlCommandAsync无法使用求助

解决EF Core中找不到ExecuteSqlCommandAsync的问题
  • 原因:EF Core 3.0及更高版本已经移除了ExecuteSqlCommandAsync方法,官方用两个更明确的方法替代了它,以此规避SQL注入风险和语法歧义。
  • 解决方案:
    1. 直接替换为新方法:
      • 若使用参数化SQL字符串,改用ExecuteSqlRawAsync:
        await Context.Database.ExecuteSqlRawAsync("UPDATE Products SET Price = {0} WHERE Id = {1}", newPrice, productId);
        
      • 若使用C#插值字符串(会自动处理参数化,安全性更高),改用ExecuteSqlInterpolatedAsync:
        await Context.Database.ExecuteSqlInterpolatedAsync($"UPDATE Products SET Price = {newPrice} WHERE Id = {productId}");
        
    2. 核对NuGet包版本:确保你安装的Microsoft.EntityFrameworkCore.Relational包版本,与项目中Microsoft.EntityFrameworkCore的主版本完全一致,版本不匹配也可能导致方法无法识别。

内容的提问来源于stack exchange,提问作者JagathNalin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 08:36:24