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.
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; }
}
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);
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()
Update (EF Core 8.0+):
EF Core 8.0 finally added support for Raw SQL queries for unmapped types via SqlQuery or SqlQueryRaw, so now you can simply use
var query = Context.SqlQueryRaw<ClaimDataView>(...);
without registering the ClaimDataView
in the model.
Original:
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>();
Then you can use Context.Query<ClaimDataView>()
in place of your current Context.Claims
:
var query = Context.Query<ClaimDataView>().FromSql(...);
Update (EF Core 3.x+):
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);
and
var query = Context.Set<ClaimDataView>().FromSql(...);