Showing results from stored procedure on view - sql

I'm trying to show the results from a stored procedure on a view. I have a ASP.NET MVC application with the following code. I used EntityFramework to generate the models.
public class ProjectsController : Controller
{
private DatabaseEntities db = new DatabaseEntities();
// GET: Projects
public ActionResult Index()
{
var projects = db.Projects.Include(p => p.Headquarter);
return View(projects.ToList(), db.CALCULATEBUDGET());
}
}
I get the following errors on this part: db.CALCULATEBUDGET()
Argument 1: cannot convert from 'System.Collections.Generic.List<TestApplication.Models.Project>' to 'string' TestApplication C:\TestApplication\TestApplication\Controllers\ProjectsController.cs 21 Active
Argument 2: cannot convert from 'System.Data.Entity.Core.Objects.ObjectResult<TestApplication.Models.CALCULATEBUDGET_Result>' to 'string' TestApplication C:\TestApplication\TestApplication\Controllers\ProjectsController.cs 21 Active
My stored procedure:
CREATE PROCEDURE dbo.CALCULATEBUDGET
AS
SELECT MonthlyRent, Budget, 100 * H.MonthlyRent/P.Budget AS RentPercentage
FROM Headquarter H, Project P
WHERE H.HeadquarterId = P.Headquarter_HeadquarterId
I'm trying to calculate how much percent the rent is from the budget. And then I want to show the results in a view.

first of all, when you return a View you need to either pass the name or leave it empty and then it works out using the defaults. You can pass a model as well, but what you've done is to pass two data items. The first one needs to be a View name:
return View( "YourViewName", yourDataModel);
The main concept of MVC is this : here is a View and here is the data for a View in the form of a model.
Directly throwing objects from a database at a view is usually a bad idea, I would suggest you decouple your things a little bit.
Have a business layer where you get the data, you map into a model object which matches what the view needs to display. Think of that as a translation layer from what your data looks like and what your View needs to display. Rule of thumb, only send to a View whatever it needs to display and nothing more.
You can combine multiple multiple data items in one data model for the View if that's what you need, but you still pass just one object to your View.

Related

Pass list from Razor page to code behind to bulk insert using Dapper

So I've created an HTML table on a Razor page as shown below. Basically I'm just calling a method that returns a list and then using a foreach to go create the rows and controls. The part I'm completely lost on is how I go about posting this data back to the server and on the code behind using that data to insert back to SQL Server. I'm using Dapper and I'd like each row of the table to represent a data row, or one object, but how do I get the data from the Razor page passed back as a list of a class? Not sure if my terminology is accurate here but can you model bind on a list of a type? Would appreciate some assistance thanks!
It seems I'm so far off track (or so few people use asp.net core and Dapper) that I'm not getting any help. But someone very helpful marked down my question without commenting - thanks so much.
I realised the key thing I was doing wrong was trying to circumvent model binding, so I created a class/type Rating that represents each row (each column as a property) and then an Assessment type/class that contains a List as one of the properties.
On the Razor page:
#foreach (Comp c in Model.GetComps())
{
count++;
Model.assessment.Ratings.Add(new Rating());
Model.assessment.Ratings[count].AchievedCompetencyID = c.AchievedCompetencyID;
Code behind:
public void OnPost()
{
using (IDbConnection con = new SqlConnection(Startup.conStr))
{
long assessID = con.Insert(assessment);
foreach (Rating r in assessment.Ratings)
{
r.AssessmentID = Convert.ToInt32(assessID);
con.Insert(r);
}
}
}

Related entities EF Count

Need help. I want count players from clubs and show how much players are playing in club. This is my View
But i want that my code show player count in club, like this
Here is my database structure :
My starting code
public int GetCountOfPlayersInClub(int clubId)
{
using (var db = new BasketDbContext())
{
return db.Player.Count(p => p.BasketBallClubId == clubId);
}
}
But what I do now, what I need write in my ActionResult Index()?
In order to display value in view, you need to pass it over model or viewbag.
In view you can call the passed variable via razor syntax (like #Viebag.CountAll).
Note that count is not very optimized in ef core and I would recommend to ran raw query for it.in testing I did , raw query is 100 times faster.

asp.net mvc calling single view from different controllers

I have 4 different ActionResult running in 2 different Controllers, I have created a partial view StudentList, I want to use same partialView as the model is same.
from 1st ActionResult I want to display StudentList by Class
from 2nd ActionResult I want to display StudentList by Class Teacher
from 3rd ActionResult I want to display StudentList by Fee Not Paid
from 4th ActionResult I want to display StudentList by Absent Student
all 4 return a Model type of Student.
with fields StudentName, ParentMobileNo
Is it possible not to create 4 different View and use single partial view or single view to display the result.
Regards
Yes. Create a shared view and pass the view name when returning the ActionResult from the controller.
return View("StudentList", model);
Or if you want to render a partial from a view:
#{ Html.RenderPartial("StudentList", model); }
Create a Partial View that will be hooked up to use your Student model.
Then create multiple actions in your controller for returning the different results.
StudentsByClass - then within this action call the relevant business layer/repository to do the query, as long as it's returning type Student (or the name of your model being used in your Partial View) it will be fine.
Then create another three actions for each of the scenarios, again calling the relevant business/repository method to do the query. Again as long as they return the same model that the Partial Student View is expecting it should work.
Then in each of the actions return the View along with the results to pass to the model like so:
return View("StudentList", model);
View should just worry about displaying model passed to it. How the model is created should be transparent to the view.
In your case,you can have a single view which just displays StudentList model passed to it. For generating this model you can have either one action method or four of them.
If you want single action method,you can pass a parameter indicating grouping.
Thanks
Prasad

How to display only specific columns of a table in entity framework?

how to display the some specific columns of table instead of whole table in entity framework.
using (DataEntities cxt = new DataEntities())
{
notes note = cxt.notes.Where(no => no.id == accID).SingleOrDefault();
return notes;
}
For this purpose, I would suggest you to make use of ViewModel like following :-
notes note = cxt.notes.SingleOrDefault(no => no.id == accID);
var model = new YourViewModel // Your viewModel class
{
ID = note.ID,
PropertyOne = note.PropertyOne, // your ViewModel Property
PropertyTwo = note.PropertyTwo
};
You can do this with QueryView.
This implies editing your model directly in XML as there is no designer support for this, but you will get an independant entity with less fields than the original one.
Advantages:
You can then query data base for this truncated entity directly (you will get only fields you need from the data base - no need to get whole entity from DB and trancate it in code)
It is good in scenarios where you want to send this truncated entity to the
client
with WCF to minimize traffic (e.g. when building big lists on client
that basically need only name and ID and no other entity specific
information).
Disadvantages:
This QueryView-based entity is read only. To make it writeable you will have to add r/w functionality yourself

Stored Proc in RIA Services

I want to load some data with a SP.
I've put a SP in a Linq to SQL Class and I don't know how to use it for loading it's data in a datagrid.
In LinqToSqlDomainService I can't figure out how to call a SP.
What steps should I use.
Any samples of this ? All samples use a table.
Thank's
This post should hopefully be of help:
http://blogs.msdn.com/brada/archive/2009/08/24/business-apps-example-for-silverlight-3-rtm-and-net-ria-services-july-update-part-24-stored-procedures.aspx
You can create empty view with the same structure of your sproc and map that stored procedure to your function in your DomainService
See sample on http://cid-289eaf995528b9fd.skydrive.live.com/self.aspx/Public/sproc.zip
I found the following excellent step-by-step guide at this site -
http://betaforums.silverlight.net/forums/p/218383/521023.aspx
1) Add a ADO Entity Data Model to your Web project; Select generate from database option; Select your Database instance to connect to.
2) Choose your DB object to import to the Model. You can expand Table node to select any table you want to import to the Model. Expand Stored Procedure node to select your Stored Precedure as well. Click Finish to finish the import.
3) Right click the DB model designer to select Add/Function Import. Give the function a name (same name as your SP would be fine) and select the Stored Procedure you want to map. If your SP returns only one field, you can map the return result to a collection of scalars. If your SP returns more than one field, you could either map the return result to a collection or Entity (if all the field are from a single table) or a collection of Complex types.
If you want to use Complex type, you can click Get Column button to get all the columns for your SP. Then click Create new Complex type button to create this Complex type.
4) Add a Domain Service class to the Web project. Select the DataModel you just created as the DataContext of this Service. Select all the entitis you want expose to the client. The service functions should be generated for those entities.
5) You may not see the Complex type in the Entity list. You have to manully add a query function for your SP in your Service:
Say your SP is called SP1, the Complex type you generated is called SP1_Result.
Add the following code in your Domain Service class:
public IQueryable<SP1_Result> SP1()
{
return this.ObjectContext.SP1().AsQueryable();
}
Now you can compile your project. You might get an error like this: "SP1_Result does not have a Key" (if you not on RIA service SP1 beta). If you do, you need to do the following in the service metadata file:
Added a SP1_Result metadata class and tagged the Key field:
[MetadataTypeAttribute(typeof(SP1_Result.SP1_ResultMetadata))]
public partial class SP1_Result
{
internal sealed class SP1_ResultMetadata
{
[Key]
public int MyId; // Change MyId to the ID field of your SP_Result
}
}
6) Compile your solution. Now you have SP1_Result exposed to the client. Check the generated file, you should see SP1_Result is generated as an Entity class. Now you can access DomainContext.SP1Query and DomainContext.SP1_Results in your Silverlight code. You can treat it as you do with any other Entity(the entity mapped to a table) class.
Calling a stored procedure is trivial. Import it as a function and then invoke the function as a member of the DDS. The return value is an ObservableCollection<> that you can use to set up the DataContext of the object you want to bind.
...unless you want to use it in a Silverlight RIA app via the magic code generated proxy, in which case your goose is cooked unless your result rows exactly match one of the entities. If you can meet that criterion, edit the DomainService class and surface a method that wraps the ObjectContext method.