对于我自己的实践,我建立一个小型ASP.NET网站,显示现有数据库的数据内容。
使用Entity Framework来处理数据库,我想在连接中使用lambda表达式。
实际我在我的数据库中有6个表:
Projects
(ID,ProjectName)Categories
(ID,CategoryName)Users
(ID,UserName)Parts
(ID,PartName)ProjectCategoryPart
(ProjectID,CategoryID,PartID,PartExists) ProjectCategoryUser
(ProjectID,CategoryID,UserID)
Project
都有n
Categories
Category
都有1
User
Project
和Category
,n
Parts
都有PartExists
- 国旗现在我想创建一个列表,其中包含表一
中的一个项目的以下信息Category User Parts Left Total Parts
Category_1 RelatedUserName PartCountLeft PartCountTotal
Category_2 RelatedUserName PartCountLeft PartCountTotal
Category_n RelatedUserName PartCountLeft PartCountTotal
这里举例说明一个代码行I实际用于从项目中获取项目数据项目:
myList = DatabaseEntities.Projects.Single(project => project.Number == sendNumber);
有人可以帮我处理创建List所需的代码吗?
到目前为止,我只能创建简单的数据库请求,因为我很难找到显示超出此范围的示例。
答案 0 :(得分:0)
正如评论中所解释的那样,您的设计可能需要一些工作,但如果您尝试专注于聚合部分,则可以解决它。如果您的类具有与此类似的导航属性:
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; }
}
接下来,我将为结果构建一个viewmodel:
public class ProjectPartViewModel
{
public string Category { get; set; }
public string Name { get; set; }
public int PartsCount { get; set; }
public int PartsExistCount { get; set; }
}
然后查询:
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();