MVC Entity Framework calling stored procedure - asp.net-mvc

I am using ASP.NET MVC 4.5 and EF. I import the stored procedures into my ADO.NET Entity Data Model. I have my .edmx and XX.tt with my StoreProcedure_Result.cs.
I use
var result = dbcontext.SP(Param).AsEnumerable().First();
My problem is that those stored procedures that have
select count(id) as Count from table
doesn't appear on my SP_Result.cs
Any ideas?

I just tried this out myself and did not see a "_Result.cs" class created either for the sproc that just returns count(). I'm guessing that a _Result.cs class does not need to be created because it is just a single int, and a specific type is not needed. I was still able to call the sproc though. You could obtain the int like this...
var result = db.getCount().First();
int i = (int)result;

Related

Entity Framework Core Database Table Valued Functions Mapping

I use EFCore 2.1 Database First approach. I'm pretty familiar with SQL syntax and prefer build queries myself rather then leave this work on EF. I use Table Valued and Scalar Functions for querying the database.
I found this for Scalar
https://learn.microsoft.com/en-us/ef/core/what-is-new/ef-core-2.0#database-scalar-function-mapping
But unfortunately nothing about Table Functions.
Is there any way to force Visual Studio grab all Table Functions and Scalar Functions and Stored Procedures from SQL Server, when I run Scaffolding?
I was using LINQ to SQL dbml designer before. Everything was extremely simple with dbml. You drag from Server Explorer drop to dbml and boom, I can use SQL Function or SP like regular C# method.
Any chance to reproduce this in EFCore?
There's no reverse engineer (aka DbContext scaffolding) support for it, but you can use FromSql() to query using table-valued functions. See these docs.
var searchTerm = "EF Core";
var blogResults = db.Blogs.FromSql(
"SELECT * FROM dbo.SearchBlogs({0})",
searchTerm);
Source : https://www.allhandsontech.com/data-professional/entityframework/entity-framework-core-advanced-mapping/
Use HasDbFunction to do a mapping, refer Microsoft doc
It requires return types to be declared as Keyless entity using HasNoKeyMicrosoft doc
Configure EF Context to expose Db function
modelBuilder.HasDbFunction(typeof(SalesContext)
.GetMethod(nameof(NameAndTotalSpentByCustomer)))
.HasName("CustomerNameAndTotalSpent");
modelBuilder.Entity<CustWithTotalClass>().HasNoKey();
Invoke Db function in calling code
_context.NameAndTotalSpentByCustomer().Where(c=>c.TotalSpent>100).ToList();
Generated SQL
SELECT [c].[Name], [c].[TotalSpent]
FROM [dbo].[CustomerNameAndTotalSpent]() AS [c]
WHERE [c].[TotalSpent] > 100

Fetching multiple records from multiple tables using stored procedure in Entity Framework in ASP.NET MVC 5

create procedure GetCityArea
as
begin
select * from CityMaster;
select * from Area;
End
This is my stored procedure GetCityArea which returns multiple record.
My exact problem is I am getting multiple record from the stored procedure, and I want to show this result in single view as separate tables. I am new in ASP.NET MVC and I want to solve this problem using Entity Framework. Please help.
You can do this using ObjectContext and the Translate method.
The gory details are here: https://msdn.microsoft.com/en-us/data/jj691402.aspx

ASP.NET MVC & Entity Framework stored procedures

My ASP.NET MVC web app needs to get data from existing database using T-SQL stored procedures. I've seen tutorials on how to do that using the code-first approach (basically for a model named Product, the Entity Framework generates stored procedures like Product_Update, Product_Delete, etc).
But in my case I can't use code-first b/c the database and the stored procedures already exist and their names don't follow this convention. What's the way to go? Any help will be appreciated. Thanks in advance.
Begin Edited 2017-03-28
If I go about using straight ADO.NET classes as Shyju and WillHua said, will data annotations on my Model data classes work? If not, how else can validation, etc be implemented?
If I follow this approach, do I need to reference Entity Framework in my project at all?
End Edited 2017-03-28
If you're using Entity Framework you could do something similar to the following:
var startDateParam = new SqlParameter("StartDate", 8) { Value = startDate };
var endDateParam = new SqlParameter("EndDate", 8) { Value = endDate };
var parameters = new[] { startDateParam, endDateParam };
var result= Context.Database.SqlQuery<CampaignReferralReportItem>("CampaignReferralReportItems #StartDate, #EndDate", parameters).ToList<CampaignReferralReportItem>();
return result;
So what you've got here is the declaration of two parameters which are passed into the Stored Procedure 'CampaignReferralReportItems'. After the query is complete, the result is mapped as closely as possible to the class CampaignReferralReportItem.
Keep in mind the order of the properties must be identical as the query results or the mapping can throw exceptions.
It's worth noting that the Context stated in the above code is your DataContext.
Also, before you start throwing this kind of code everywhere. It might be worthwhile looking at the Repository pattern
I'd suggest either using Dapper, which I am strating to use, and love for it's speed - or, Entity Framework, and 'Update model from Database' - so, a database first approach, where the references to the procs are pulled in.
But, I'd suggest Dapper, as it's pretty simple and quick.

Using EF and MVC together

I would like to use Entity Framework 5 from which I can use one MVC Model that can span two or more databases.
Is this possible?
In other words, have one EF model that can use two or more databases. Because with MVC, you can only use 1 model in a View. Some of the data with some of the Views can come from different databases. In order to use the model binder in MVC and map it to EF 5 columns, I would need to accomplish this.
ASP.NET MVC is NOT dependent on Entity Framework.
ASP.NET MVC is a framework for building web application that stick with the Model View Controller pattern. It is not bounded to Entity framework. It can work with any data access technologies like LINQ2SQL / Entity Framework / Pure ADO.NET etc.. that means you can develop MVC application with or without using Entity Framework.
I assume you want to get data from 2 different databases and load a model object. You can do that by writing a select query which gets data from 2 databases and put that in a Stored procedure and put that proc in your database which your DbContext is communicating with. Then execute the stored proc and load the Model object.
a sample procedure which gets data from 2 databases
CREATE PROCEDURE GetCustomer(#id int)
AS
BEGIN
SELECT C.ID,A.DateReceived
FROM FirstServerName.DbName.dbo.Customer C
INNER JOIN SecondServerName.DbName.dbo.Applications A
ON A.CustomerID=C.CustomerID
AND A.CustomerID=#id
END
To execute the stored proc with Entity framework, you can use Database.SqlQuery method
var idParam = new SqlParameter { ParameterName = "#Id", Value = 414};
var result = context.Database.SqlQuery<Customer>
("exec GetCustomer #Id", idParam).ToList();
This will execute your proc and load the data to an instance of Customer class, assuming the result set structure and your model class structure look similar.
You may need to adjust the permissions of the stored proc to read data from the relevant databases /tables.
What Shyju is saying is that MVC doesn't care or know anything about your Entity Framework data model or database. As such, the idea that an MVC model can span two databases is like saying an airplane can span two hammers.
As above the M in MVC is whatever you want it to be. Microsoft don't specify what Model actually is. It certainly doesn't have to be an EF Model (although some code samples from MS use that as an example)
I'd suggest that M should be a ViewModel and should be unrelated to your data layer. Then use a tool like Automapper to map from a domain model to a ViewModel. The ViewModel encapsulates the data you want to show and any specific web view specific information that you want to display. Then when you post back the ViewModel you can use that to update the domain models appropriate fields etc and persist that to both databases. This is a good article on the subject of ViewModels http://lostechies.com/jimmybogard/2009/06/30/how-we-do-mvc-view-models/

ASP.NET MVC Partial Model Binding from Stored Procedures

Currently, I have a set of stored procedures which are called to populate different fields on a page. I am calling the stored procedures from the LINQ to SQL class that I dropped them on, which works fine. However, it automatically generates (StoredProcedureName)Result class names which I have to work with.
Is there anyway to take a stored procedure and bind the result to multiple classes? For example I have a stored procedure that gets the information for a blog post. I want to bind that data into a Post class and a User class (for the author), however I am not retrieving all of the data from the stored procedure to fill an entire Post object or User object (the stored procedure only returns the title, content, and author name).
What is the best way to handle this scenario? I am open to changing the stored procedure but I would rather not have to return data that I am not going to use just to populate a full object and I cannot use LINQ to SQL to query the database.
You can create a partial of your DataContext and write a method that returns IMultipleResults, binding to each of your respective classes with a [ResultType(typeof(ClassName))], as shown here:
http://msdn.microsoft.com/en-us/library/bb399371.aspx
Or, you can store the results of the stored procedure in a variable and then LINQ-Select new instances of your target classes like this:
var result = dataContext.your_stored_proc();
var post = result.Select(s => new Post { Id = result.Id, Title = result.Title });
You can use this library:
https://github.com/mrmmins/C-StoreProcedureModelBinding
This classes are using reflection, and you need include it in your project and create an instance of Generic.cs

Resources