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

如何在.NET 8 Blazor Server中从SQL Server存储过程填充复杂对象列表?

解决Blazor Server调用SQL Server存储过程返回只读日志数据的问题

针对你当前的代码问题,按以下步骤修正即可实现需求:

1. 完善数据库上下文配置

你的ApplicationDbContext中未注册LogItem这个无键实体,需要添加对应的DbSet并确保EF Core识别它是无键类型:

using Microsoft.EntityFrameworkCore;

namespace MyAdmin.Data
{
  public class ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : IdentityDbContext<ApplicationUser>(options)
  {
    public virtual DbSet<ModernQuoteRequest> ModernQuoteRequests { get; set; }
    // 添加LogItem的DbSet
    public virtual DbSet<LogItem> LogItems { get; set; }
    
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
      base.OnModelCreating(modelBuilder);
      // 显式配置该实体为无键(配合[Keyless]特性双重保障)
      modelBuilder.Entity<LogItem>().HasNoKey();
    }
  }
}

2. 修正存储过程调用代码

你调用时的类型LogItems是错误的,应该使用实体类名LogItem,同时可以直接用上下文里定义的LogItems属性:

using var context = ContextFactory.CreateDbContext();

// 调用存储过程并转为列表
var logItems = await context.LogItems.FromSqlRaw("EXEC dbo.GetLogItems").ToListAsync();

3. 优化与注意事项

  • 参数安全:如果存储过程需要传入参数,必须使用参数化查询避免SQL注入,示例:
    var statusParam = new SqlParameter("@Status", "Success");
    var logItems = await context.LogItems.FromSqlRaw("EXEC dbo.GetLogItems @Status", statusParam).ToListAsync();
    
  • 只读优化:因为日志是只读数据,加上AsNoTracking()可以跳过EF Core的变更追踪,提升性能:
    var logItems = await context.LogItems.FromSqlRaw("EXEC dbo.GetLogItems").AsNoTracking().ToListAsync();
    
  • 列名匹配:确保存储过程返回的列名与LogItem类的属性名完全一致(SQL Server默认大小写不敏感,但建议保持一致避免意外)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 11:41:21