在Views / Home中有一个文件: Opinion.cshtml 。
@model Aquapark.ViewModels.OpinionViewModel
@{
ViewBag.Title = "Opinia";
Layout = "~/Views/Shared/_StoreLayout.cshtml";
}
<h2>Opinia</h2>
<div style="margin-top: 20px; line-height: 22px;">
<div class="opinion-box">
@foreach (var opinions in Model.Opinions)
{
<div class="opinion-box-content">
<div class="opinion-box-content-inside">@opinions.Content</div>
<div class="date">@opinions.Date</div>
</div>
<div class="opinion-author">@opinions.PersonId</div>
}
</div>
</div>
我在 ViewModel 文件夹(已创建)中有文件: OpinionViewModel.cs 。
using Aquapark.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Aquapark.ViewModels
{
public class OpinionViewModel
{
public IEnumerable<Opinion> Opinions { get; set; }
public IEnumerable<Person> Authors { get; set; }
}
}
Person.cs
namespace Aquapark.Models
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Spatial;
[Table("Person")]
public partial class Person
{
[Key]
public int PersonId { get; set; }
[Required]
public long Pesel { get; set; }
[Required]
[StringLength(30, ErrorMessage = "Imię nie może zawierać więcej niż 30 znaków.")]
[Display(Name = "Imię")]
public string FirstName { get; set; }
[Required]
[StringLength(60, ErrorMessage = "Nazwisko nie może zawierać wiecej niż 60 znaków.")]
[Display(Name = "Nazwisko")]
public string LastName { get; set; }
[Required]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{dd/mm/yyyy}", ApplyFormatInEditMode = true)]
[Display(Name = "Data urodzenia")]
public DateTime DateOfBirth { get; set; }
public virtual Client Client { get; set; }
public virtual Employee Employee { get; set; }
public string FullName
{
get
{
return FirstName + " " + LastName;
}
}
}
}
HomeController.cs
public class HomeController : Controller
{
private AquaparkContext db = new AquaparkContext();
// GET: Home
public ActionResult Index()
{
var opinions = db.Opinion.ToList();
//var randomOpinions = db.Opinion.Where(a => a.Date >= DateTime.Parse("2015-01-01")).OrderBy(g => Guid.NewGuid()).Take(6).ToList();
var authors = from p in db.Person
join o in db.Opinion
on p.PersonId equals o.PersonId
select new
{
p.FullName
};
var vm = new OpinionViewModel()
{
Opinions = opinions,
//Authors = authors,
};
return View(vm);
}
public ActionResult StaticContent(string viewname)
{
return View(viewname);
}
问题: 我想显示意见的作者(FirstName和LastName)。我尝试使用LINQ来选择数据(HomeController var authors),但我不能归因于集合作者,因为存在错误。
错误2无法隐式转换类型 &#39; System.Linq.IQueryable&#39;至 &#39; System.Collections.Generic.IEnumerable&#39 ;.一个 存在显式转换(您是否错过了演员?)C:\ Users \ Asus N551 \ OneDrive \ Documents \ Aquapark \ Aquapark \ Controllers \ HomeController.cs 31 27水上乐园
如何正确解决问题?
答案 0 :(得分:0)
var opinions = db.Opinions
.Select(x => new
{
x.Id,
AuthorFullName = x.Author.FirstName + " " + x.Author.LastName,
Body = x.Body
})
.ToList();