I have searched a few posts, but have come up short. I am using EF6 code first trying to get results from a stored procedure that is already setup in a database. My application is simple, it takes data from two different servers, performs some business logic, and then shows the user. I can use the .edmx
file fine, which maps the function in the xml file. When I use Power Tools to show myself the XML file I do not see the function import from my code below so I am either missing a setup or I cannot use ExecuteFunction()
.
Can I use the ExecuteFunction()
with code first? My stored procedure only returns records. The reason I have this setup is because the stored procedure feeds another application and we want to keep all the changes to the query in one place (SSMS). I realize I could use ExecuteStoredQuery
/ ExecureStoredCommand
, but I wanted to stick to the convention if I were to use the .edmx
model.
If I can use ExecuteFunction
, where and how do I configure my DbContext
to recognize the stored procedure? With my setup below I receive the error
The FunctionImport {0} could not be found in the container {1}
Can I use Fluent API? Thanks.
public class JobContext : DbContext
{
public JobContext()
: base("name=JobContext")
{
// My context will only define a slice of the database
Database.SetInitializer<JobContext>(null);
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.ComplexType<Job>();
}
public virtual ObjectResult<Job> uspGetJobs(string startDate)
{
var startDateParameter = startDate != null ?
new ObjectParameter("startDate", startDate) :
new ObjectParameter("startDate", typeof(string));
return ((IObjectContextAdapter)this).ObjectContext.<Job>("uspGetJobs", startDateParameter);
}
}
In code first approach first we create classes (Code) and using this code database will be get generated. We need not use edmx file in code first approach.
EF Core already supports querying data from stored procedures. This feature will allow mapping the inserts, updates, and deletes generated by SaveChanges to stored procedures in the database.
since it was a read only stored procedure I ended up doing this instead of trying to mimick the generated model.
public virtual List<Jobs> uspGetJobs(string startDate)
{
var startDateParameter = startDate != null ?
new SqlParameter("startDate", startDate) :
new SqlParameter("startDate", typeof(string));
return this.Database.SqlQuery<PlannedJobs>("uspGetPlannedJobs @startDate, @locationCode", startDateParameter, locationCodeParameter).ToList();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With