c# - 在 Entity Framework 核心中执行存储过程而不期望映射到 dbset

标签 c# stored-procedures .net-core entity-framework-core

我正在研究 .NET CORE,Entity Framework 核心。我有需要从 .NET 类执行的存储过程。我的存储过程需要一些“上下文”,但我不知道如何处理这个问题,尽管我有 dataView,这是最终的异常。

如果我可以使用我的 dataView 而不是 context.dataModel 类,当前实现 (Context.Claims.FromSql),我会很受伤

数据 View

public class ClaimDataView
{
    public Guid ClaimId { get; set; }
    public int IdNum { get; set; }
    public string Value { get; set; }
    public DateTime ExpirationDate { get; set; }
    public ClaimAttributionActions Action { get; set; }
    public bool ActiveStateForRole { get; set; }

}

存储过程调用

public Guid UserId { get; set; }
public Guid ClientId { get; set; }
public Guid ConsultationId { get; set; }

  var userParam = new SqlParameter("@UserVal", UserId);
  var clientParam = new SqlParameter("@ClientVal", ConsultationId);
  var consultationParam = new SqlParameter("@ConsultationVal", ConsultationId);

 //**************need help in following line
  var query = Context.Claims.FromSql("EXECUTE dbo.ListUserClaims @userId=@UserVal, @clientId=@ClientVal, @consultationId=@ConsultationVal"
            , userParam, clientParam, consultationParam);

新更新

moduleContext 类

  protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
       //other models....
       modelBuilder.Query<ClaimDataView>();
    }

存储过程执行自

 var query = Context.Query<UserDataView>().FromSql("EXECUTE dbo.ListUserClaims @userId=@UserVal, @clientId=@ClientVal, @consultationId=@ConsultationVal"
            , userParam, clientParam, consultationParam);

错误

System.InvalidOperationException: Cannot create a DbSet for 'UserDataView' because this type is not included in the model for the context.
 at Microsoft.EntityFrameworkCore.Internal.InternalDbQuery`1.get_EntityType()

最佳答案

您可以利用 Query Types在 EF Core 2.1 中引入。

首先您需要将您的类注册为查询类型:

modelBuilder.Query<ClaimDataView>();

然后你可以使用Context.Query<ClaimDataView>()代替您当前的 Context.Claims :

var query = Context.Query<ClaimDataView>().FromSql(...);

更新(EF Core 3.x+):

从 EF Core 3.0 开始,查询类型已变为 consolidated with entity types并重命名为 Keyless Entity Types , 所以对应的代码是

modelBuilder.Entity<ClaimDataView>().HasNoKey().ToView(null);

var query = Context.Set<ClaimDataView>().FromSql(...);

关于c# - 在 Entity Framework 核心中执行存储过程而不期望映射到 dbset,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52003432/

相关文章:

c# - 在 asp.net MVC 中用图片替换站点标题

c# - 以编程方式启用/禁用硬件设备

c# - 无法使用 C# 在 URL 中发送大括号和空格

c# - Caliburn Micro Datagrid 绑定(bind)

c# - 找不到任何已安装的.NET Core SDK

c# - 使用System.Text.Json获取嵌套属性

mysql - MySQL 中带有条件变量的存储过程

Php mysqli 和存储过程

sql - 本月第 3 个 <day_of_week> - MySQL

asp.net-core - .NET-Core 字节数组到图像