How to call stored procedure in EF Core v2.1 and set result to custom model? entity-framework-core


In EF 6, I use this code that calls a stored procedure and returns result as a custom model.

var pShippingMethodId = _dataProvider.GetParameter();

pX.ParameterName = "X";
pX.Value = x;
pX.DbType = DbType.Int32;

var pStoreId = _dataProvider.GetParameter();
pY.ParameterName = "Y";
pY.Value = y;
pY.DbType = DbType.Int32;

var pLanguageId = _dataProvider.GetParameter();
pZ.ParameterName = "Z";
pZ.Value = z;
pZ.DbType = DbType.Int32;

var parameters = " @" + pX.ParameterName + ", @" + pY.ParameterName + ", @" + pZ.ParameterName;

// invoke stored procedure
var result = _dbContext.SqlQuery<AvailableDeliveryDateTimeModel>(Constants.LoadAvailableDeliveryDateTimesStoredProcedureName + parameters,pX, pY, pZ).ToList();

I want migrate this code to EF Core, but I can't find appropriate methods in EF Core

8/26/2018 7:08:10 AM

Accepted Answer

You can utilize the Query Types introduced in EF Core 2.1.

First you need to register you class as query type:


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



var query = Context.Set<ClaimDataView>().FromSql(...);
4/2/2020 12:35:12 PM

Popular Answer

If you are not on version 2.1, you will need to add:

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

to your moduleContext. And add NotMapped to your class:

public class ClaimDataView

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow