using stored procedure in entity framework
You need to create a model class that contains all stored procedure properties like below. Also because Entity Framework model class needs primary key, you can create a fake key by using Guid.
public class GetFunctionByID
{
[Key]
public Guid? GetFunctionByID { get; set; }
// All the other properties.
}
then register the GetFunctionByID
model class in your DbContext
.
public class FunctionsContext : BaseContext<FunctionsContext>
{
public DbSet<App_Functions> Functions { get; set; }
public DbSet<GetFunctionByID> GetFunctionByIds {get;set;}
}
When you call your stored procedure, just see below:
var functionId = yourIdParameter;
var result = db.Database.SqlQuery<GetFunctionByID>("GetFunctionByID @FunctionId", new SqlParameter("@FunctionId", functionId)).ToList());
After importing stored procedure, you can create object of stored procedure pass the parameter like function
using (var entity = new FunctionsContext())
{
var DBdata = entity.GetFunctionByID(5).ToList<Functions>();
}
or you can also use SqlQuery
using (var entity = new FunctionsContext())
{
var Parameter = new SqlParameter {
ParameterName = "FunctionId",
Value = 5
};
var DBdata = entity.Database.SqlQuery<Course>("exec GetFunctionByID @FunctionId ", Parameter).ToList<Functions>();
}
You can call a stored procedure using SqlQuery
(See here)
// Prepare the query
var query = context.Functions.SqlQuery(
"EXEC [dbo].[GetFunctionByID] @p1",
new SqlParameter("p1", 200));
// add NoTracking() if required
// Fetch the results
var result = query.ToList();
// Add some tenants to context so we have something for the procedure to return! AddTenentsToContext(Context);
// ACT
// Get the results by calling the stored procedure from the context extention method
var results = Context.ExecuteStoredProcedure(procedure);
// ASSERT
Assert.AreEqual(expectedCount, results.Count);
}