我有这个viewmodel
public class TipoProyectoViewModel
{
public string Category{ get; set; }
public IEnumerable<ProjectType> Type{ get; set; }
}
我按类型
订购了所有项目var category = _dbContext.Categoria
.Include( c => c.TipoProyecto )
.Where( c => c.CategoryId == CategoryId )
.GroupBy( e => e.CategoryName )
.Select( e => new TipoProyectoViewModel() {
Category = e.Key,
Tipo = e.SelectMany( p => p.ProjectType )
} )
.FirstOrDefault();
此代码返回类似
的内容Home //project category as string in my viewmodel
{
Ienmuerable1
Ienumerable2 //a list of ProjectType
.....
}
Home //project category as string
{
Ienmuerable1
Ienumerable2 //a list of ProjectType
.....
}
现在我想在我的viewmodel中添加一个新属性,并从数据库中获取它
public class TipoProyectoViewModel
{
public string Glyphicons { get; set; }
public string Category { get; set; }
public IEnumerable<ProjectType> Type { get; set; }
}
Glyphicons来自我的类别表
public class Categoria
{
[Required]
public Guid Id { get; set; }
public string CategoryName { get; set; }
public ICollection<ProjectType> ProjectType { get; set; }
public string Glyphicons { get; set; } <<<<<glyphicons
}
我应该如何修改实体框架查询?
var category = _dbContext.Categoria
.Include( c => c.TipoProyecto )
.Where( c => c.CategoryId == CategoryId )
.GroupBy( e => e.CategoryName )
.Select( e => new TipoProyectoViewModel() {
Category = e.Key,
glyp=...,
Tipo = e.SelectMany( p => p.ProjectType )
} )
.FirstOrDefault();
答案 0 :(得分:1)
ViewModels与您的数据库实体类型正交。
您应该直接创建ViewModel对象并在查询之外填充它,如下所示:
public IActionResult Get()
{
TipoProyectoViewModel viewModel = new TipoProyectoViewModel();
using( var dbContext = ... )
{
var catgoryGroup = dbContext.Categoria
.Include( c => c.TipoProyecto )
.Where( c => c.CategoryId == CategoryId )
.GroupBy( e => e.CategoryName )
.FirstOrDefault();
viewModel.Category = catgoryGroup.Key;
viewModel.Tipo = categoryGroup
.SelectMany( p => p.ProjectType )
.ToList(); // Always call ToList() because you should never pass an IQueryable to your View!
viewModel.Glyphicons = dbContext
.Select( /* your query to get data for this property */ );
}
return this.View( viewModel );
}