查询嵌套的IEnumerable模型类-视图的组合模型有两个类



我有一个由两个嵌套类组成的组合ViewModel。一个是IEnumerable,另一个不是。原因是我想同时使用两者,所以在视图中我可以使用@foreach和@Html。DisplayNameFor。视图正在使用@model Project。ViewModels。BlogCommentCombinedViewModel

我发现了一篇关于如何使用嵌套模型的文章,但是我在尝试使用IEnumerable嵌套类时遇到了一个错误,我的LINQ查询显示";无法将类型BlogViewModel隐式转换为系统。集合。通用的IEnumerable<项目ViewModels。BlogViewModel>

如何显式强制转换,或者有更好的方法吗?

控制器

var blogResult = from a in _db.Users
join b in _db.blog on a.Id equals b.userID
select new BlogCommentCombinedViewModel
{

bvm = new BlogViewModel
{ GETTING ERROR HERE:
"cannot implicity convert type BlogViewModel to Systems.Collections.Generic.IEnumerable<Project.ViewModels.BlogViewModel>" An explicit conversion exist - are you missing a cast
}

lcvm = new LeaveCommentViewModel
{
//binding data in here
}
} ;

组合视图模型

public class BlogCommentCombinedViewModel
{
public IEnumerable<BlogViewModel> bvm { get; set;}
public LeaveCommentViewModel lcvm { get; set; }
}
public class BlogViewModel
{
[Key]
public int blogID { get; set; }
public string blogTitle { get; set; }
public string blogContent { get; set; }
public string userID { get; set; }
public DateTime publishedDate { get; set; }
[NotMapped]
public string firstName { get; set; }
[NotMapped]
public string lastName { get; set; }
[NotMapped]
public class LeaveCommentViewModel
{
[Key]
public int commentID { get; set; }
[Display(Name = "Comment")]
[MinLength(5, ErrorMessage = "Comment is too short")]
public string comment { get; set; }
public string reply { get; set; }
public int blogID { get; set; }
public string userID { get; set; }
}

问题是IEnumerable<BlogViewModel>!=CCD_ 2。即使您只创建了一个元素,也需要将其封装在IEnumerable<BlogViewModel>或实现该接口的东西中,例如List<T>

相反,试试这个:

// Definition
public class BlogCommentCombinedViewModel
{
public IEnumerable<BlogViewModel> bvm { get; set;}
public LeaveCommentViewModel lcvm { get; set; }
}
// Query
var blogResult = from a in _db.Users
join b in _db.blog on a.Id equals b.userID
select new BlogCommentCombinedViewModel
{                                  
bvm = new[]
{ 
new BlogViewModel() // etc
},
lcvm = new LeaveCommentViewModel
{
// binding data in here
}
};

这将创建一个包含一个BlogViewModel项的数组,该项可以隐式转换为IEnumerable<T>

测试代码

这在LINQPad:中编译和运行

var users = new[] { new User(42) };
var blog = new[] { new Blog(42) };
var test = from u in users
join b in blog on u.Id equals b.UserId
select new BlogCommentCombinedViewModel
{
bvm = new[]
{
new BlogViewModel() // etc
},
lcvm = new LeaveCommentViewModel
{
// binding etc
}
};
test.Dump();
public record User(int Id);
public record Blog(int UserId);
public class BlogCommentCombinedViewModel
{
public IEnumerable<BlogViewModel> bvm { get; set; }
public LeaveCommentViewModel lcvm { get; set; }
}
public class BlogViewModel
{
// etc
}
public class LeaveCommentViewModel
{
// etc
}

最新更新