一尘不染

在实体Framework Core中执行存储过程,而不期望映射到dbset

c#

我正在.NET CORE,实体框架核心。我已经存储了需要从.NET类执行的过程。我的存储过程的编号为“
Context”,尽管我有dataView这是最终的例外,但我不知道如何处理。

如果我可以使用dataView而不是context.dataModel类,那么我会更痛苦,当前实现(Context.Claims.FromSql)

dataView

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()

阅读 430

收藏
2020-05-19

共1个答案

一尘不染

您可以利用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开始,查询类型已与实体类型合并,并重命名为Keyless Entity
Types
,因此相应的代码为

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

var query = Context.Set<ClaimDataView>().FromSql(...);
2020-05-19