For my own practice I'm building a small ASP.NET website that shows data content of an existing database.
To work with the database I'm using Entity Framework and I want to use lambda expressions in connection.
Actual I got 6 tables in my database:
Projects
(ID, ProjectName) Categories
(ID, CategoryName) Users
(ID, UserName) Parts
(ID, PartName) ProjectCategoryPart
(ProjectID, CategoryID, PartID, PartExists) ProjectCategoryUser
(ProjectID, CategoryID, UserID)
Project
has n
Categories
Category
has 1
User
Project
and Category
there are n
Parts
with an PartExists
-Flag Now I want to create a list that contains the following information for one of the projects inside of table one
Category User Parts Left Total Parts
Category_1 RelatedUserName PartCountLeft PartCountTotal
Category_2 RelatedUserName PartCountLeft PartCountTotal
Category_n RelatedUserName PartCountLeft PartCountTotal
Here for example one code Line I'm actually using to get the data of a project out of the table Projects:
myList = DatabaseEntities.Projects.Single(project => project.Number == sendNumber);
Can someone help me with the code I need to create the List?
Up to now I'm only able to create simple database requests because it was hard for me to find examples that are showing more than this.
As explained in the comments, your design may need some work, but if you are trying to focus in on the aggregation portion you can work around it. If your classes have navigation properties similar to this:
public class Project
{
public int Id { get; set; }
public string ProjectName { get; set; }
// if you want multiple users you will need to change this
public int UserId{ get; set; }
public User User { get; set; } // nav to user
public ICollection<ProjectPart> ProjectParts { get; set; }
}
public class ProjectPart
{
public int PartId { get; set; } // Be consistent and call this ID as below
public string PartName { get; set; }
public bool? PartExists { get; set; }
public string CategoryName { get; set; }
public int ProjectId { get; set; }
public Project Project { get; set; } // nav to project
}
public class User
{
public int Id { get; set; }
public string UserName{ get; set; }
public ICollection<Project> Projects { get; set; }
}
Next, I would build a viewmodel for the results:
public class ProjectPartViewModel
{
public string Category { get; set; }
public string Name { get; set; }
public int PartsCount { get; set; }
public int PartsExistCount { get; set; }
}
Then the query:
var projectPartCounts = context.ProjectParts.AsNoTracking()
.GroupBy(pp => new { pp.CategoryName, pp.Project.User.UserName })
.Select(g => new PropjectPartsViewModel {
Category = g.Key.CategoryName,
Name = g.Key.UserName,
PartsCount = g.Count(),
PartsExistCount = g.Count(pp => pp.PartsExist == true)
})
.ToList();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.