Hi,
In my .Net Core based web application I am accessing and using a MSSQL database. Through entity framework. Initially there were only tables.
I have now written a stored procedure and am looking for ways to call it through my EF code. I have searched some links. Some of them are suggesting things like FromSql, ExecuteSqlCommand etcetc. but I am so confused as to how to put the thing together. The
trouble here is, I wrote the SP on the MSSQL db and it is not based on one specific table but yields a result based on the join on several tables as you will see below. Do I need to add something in my applicationDbContext class? If so how? Or do I add some
kind of scaffolding or migration to incorporate this newly written SP into my context?
I'll provide some of the relevant code:
1. my SP --
create procedure [dbo].[sp_GetAllOrders] @Id bigint=null as begin begin try select p.product_name, o.order_id, o.product_quantity, o.discount_perc, o.order_date, o.total_price, c.customer_email from Orders o inner join Customers c on o.customer_id=c.Id inner join Products p on p.Id=o.product_id where c.Id=@Id end try begin catch select error_message(), error_severity(), error_number(), error_state() end catch end
2. my appdbcontext --
public class ApplicationDbContext: DbContext
{
public ApplicationDbContext(DbContextOptions options)
: base(options)
{
}
public DbSet<Product> Products { get; set; }
public DbSet<Customer> Customers { get; set; }
public DbSet<Order> Orders { get; set; }
}
Now, in a WebApi method, I am trying to call this SP and show the results. I have a sample/model class called OrderSummary which is supposed to get mapped to the data returned by the SP.
4. OrderSummary --
public class OrderSummary
{
public string product_name { get; set; }
public string order_id { get; set; }
public int product_quantity { get; set; }
public int discount_perc { get; set; }
public DateTime order_date { get; set; }
public int total_price { get; set; }
public string customer_email { get; set; }
}
So what do I do next? How to go about this task? Someone please help me step by step, as I am quite confused with this at the moment; any way I can call this SP [by passing the necessary parameter] through my instance of appdbcontext? Please show me,
Many Thanks in advance,