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

时间:2018-08-24 11:24:21

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

我正在研究.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()

2 个答案:

答案 0 :(得分:11)

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

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

modelBuilder.Query<ClaimDataView>();

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

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

答案 1 :(得分:3)

如果您没有使用2.1版,则需要添加:

public DbSet<ClaimDataView> ClaimDataView { get; set; }

到您的moduleContext。 并将NotMapped添加到您的班级:

[NotMapped]
public class ClaimDataView
相关问题