我有2个型号:
class User
{
int Id { get; set; }
string Name { get; set; }
virtual HashSet<Book> Books { get; set; }
}
class Book
{
int Id { get; set; }
string Name { get; set; }
int UserId { get; set; }
byte[] CoverImage { get; set; }
virtual User User { get; set; }
}
和一个包含用户的ModelView,以及最新Book中的字段:
class UserViewModel
{
int Id { get; set; }
string Name { get; set; }
string LatestBookName { get; set; }
bool hasCoverImage { get; set; }
}
我在从数据库返回的数据中填充bool属性时遇到了一些麻烦。获取用户及其书籍很简单,但转换为viewModel证明更难。
var usersAndBooks = dbContext.Users.Include(Books); // pseudocode here, but the real thing works
这是我需要帮助的地方:
var viewModel = usersAndBook.Select(u => new UserViewModel()
{
Id = u.Id,
Name = u.Name,
LatestBookName = u.Books.Count > 0 && u.Books.OrderByDescending(b => b.Id).FirstOrDefault().Name, //works OK
//neither of these work:
//hasCoverImage = u.Books.Count > 0 && c.Books.OrderByDescending(b => b.Id).First().CoverImage.Any()
//hasCoverImage = u.Books.Count > 0 && c.Books.OrderByDescending(b => b.Id).First().CoverImage.Length > 0
}
我尝试通过查看字节数组来设置hasImage值,但是会出现运行时错误:
&#34; DbIsEmptyExpression需要一个集合参数。\ r \ n \ nParameter name:argument&#34;
代表.Any(
)
&#34; LINQ表达式节点类型&#39; ArrayLength&#39; LINQ不支持 实体。&#34;
代表.Length > 0
答案 0 :(得分:0)
我在这里找到答案:http://www.nilzorblog.com
在这里:StackOverflow post answered by @Habib
这有效:
var viewModel = usersAndBook.Select(u => new UserViewModel()
{
Id = u.Id,
Name = u.Name,
LatestBookName = u.Books.Count > 0
&& u.Books.OrderByDescending(b => b.Id).FirstOrDefault().Name,
//this does work:
hasCoverImage = u.Books.Count > 0
&& SqlFunctions.DataLength
(c.Books.OrderByDescending(b => b.Id).First().CoverImage) > 0
}
您需要使用System.Data.Entity.SqlServer;