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.
Related
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);
}
}
}
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.
We are having som performance issue with EF and I want to try rewrite a query to inline sql. However I am having some difficulties, it is probably just a noob issue.
Lets say I have 3 classes: License, GroupLicense and Product
public class License
{
//stuff
Product MyProduct{get;set}
}
public class GroupLicense:License
{
// more stuff
}
public class Product
{
//product info stuff
}
Now I need to fetch some Grouplicenses depending on some requirements. However doing it with the datacontext and linq takes 2 minutes.
Something similar to this
var institutionLicenses = db.GroupLicenses
.Include(lic => lic.Product).Where(x => productIds.Contains(x.Product.Id) && x.LicenseStatus == StatusEnum.Active).ToList();
I want to do the same query using inline sql similar to this: I join the tables so all the primitive fields are okay.
var gl = db.Database.SqlQuery<GroupLicense>("select * from GroupLicense as g left join Licenses on g.Id =Licenses.Id").ToList();
(It is just example code - I know it is not working :))
However when executing, The base product property on License is null, all the primitive fields are there.
What do I need to change in my sql statement to make it work?
I am new in ASP.NET MVC 4. In my project I am using Code First technique in of EF. I want to retrieve some data from database and I used following code for this :
List<SelectListItem> ls = new List<SelectListItem>();
var lm = from m in db.BOs //fetch data from database
select m;
foreach (var temp in lm)
{
ls.Add(new SelectListItem() { Text = temp.Name, Value = temp.Id.ToString() });
}
But when execution pointer move inside foreach it immediately come back out of the loop showing return ls value Count = 0. Code does not giving me any error while running that's why I am not getting where is going wrong.
UPDATE: I found something new this problem. When I kept mouse pointer over var lm; it shows me query and in query table name in FROM clause is not that one in my SQL database. My SQL table name is BO and in query it is taking BOes. I don't know from where this name is coming. So How I overcome this??
decorate your BO class with Table("BO") to specify the table name (attribute is in System.ComponentModel.DataAnnotations.Schema namespace)
[Table("BO")]
public partial class BO
{
...
Write following code inside DbContext class :
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
The modelBuilder.Conventions.Remove statement in the OnModelCreating method prevents table names from being pluralized. If you didn't do this, the generated tables would be named Students, Courses, and Enrollments. Instead, the table names will be Student, Course, and Enrollment. Developers disagree about whether table names should be pluralized or not. This tutorial uses the singular form, but the important point is that you can select whichever form you prefer by including or omitting this line of code.
I'm using the MVC 4 template with VS 2012. I have enabled a comments section which stores the logged in user's UserId to a table. When I display the comments I want to display the user's user name and email from the UserProfiles table.
I've tried the following code:
public static string GetUserName(int userId)
{
using (var db = new UsersContext())
{
return db.UserProfiles.Single(x => x.UserId == userId).UserName;
}
}
But I get an exception:
The model backing the 'UsersContext' context has changed since the database was created. Consider using Code First Migrations to update the database (http://go.microsoft.com/fwlink/?LinkId=238269).
Any suggestions?
The exception is pretty descriptive. Your model does not reflect what your database look like. I recommend you to read this about code first migrations, basically what migrations mean is that you update your database to match your models, its done with one line of command in VS.
Hope this helps
Also I would recommend you to use .Find() or .First() instead of .Single()