在实体Framework Core中执行存储过程,而不期望映射到dbset [英] execute stored procedure in entity Framework Core without expecting map to dbset
问题描述
我正在研究.NET CORE,实体框架核心。我已经存储了需要从.NET类执行的过程。我的存储过程带有'Context'数,我不知道该如何处理,尽管我有dataView这是最终的例外。
I am working on .NET CORE, Entity Framework core. I have stored procedure that I need to execute from .NET class. My stored procedure takes number of 'Context' and I don't know how to deal this, although I have dataView which is final exception.
如果可以使用,我会更伤人我的dataView而不是context.dataModel类,当前实现(Context.Claims.FromSql)
I wounder if I can use my dataView instead of context.dataModel class, current implementation (Context.Claims.FromSql)
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; }
}
存储过程调用
stored-Procedure call
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类
new update
moduleContext Class
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
//other models....
modelBuilder.Query<ClaimDataView>();
}
存储过程从
执行
Stored Procedure executing from
var query = Context.Query<UserDataView>().FromSql("EXECUTE dbo.ListUserClaims @userId=@UserVal, @clientId=@ClientVal, @consultationId=@ConsultationVal"
, userParam, clientParam, consultationParam);
错误
error
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()
推荐答案
您可以使用查询类型是EF Core 2.1中引入的。
You can utilize the Query Types introduced in EF Core 2.1.
首先,您需要将类注册为查询类型:
First you need to register you class as query type:
modelBuilder.Query<ClaimDataView>();
然后您可以使用 Context.Query< ClaimDataView>()
代替您当前的 Context.Claims
:
Then you can use Context.Query<ClaimDataView>()
in place of your current Context.Claims
:
var query = Context.Query<ClaimDataView>().FromSql(...);
更新(EF Core 3.x + :
从EF Core 3.0开始,查询类型为与实体类型合并并重命名为无键实体类型,因此相应的代码为
Starting with EF Core 3.0, query types have been consolidated with entity types and renamed to Keyless Entity Types, so the corresponding code is
modelBuilder.Entity<ClaimDataView>().HasNoKey().ToView(null);
和
var query = Context.Set<ClaimDataView>().FromSql(...);
这篇关于在实体Framework Core中执行存储过程,而不期望映射到dbset的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!