使用以下模型:
public class Person
{
public int PersonId { get; set; }
[Display(Name = "First Name")]
public string FirstName { get; set; }
[Display(Name = "Middle Name(s)")]
public string MiddleNames { get; set; }
public string Surname { get; set; }
public string Name
{
get
{
List<string> name = new List<string>();
name.Add(this.FirstName);
name.Add(this.MiddleNames);
name.Add(this.Surname);
return String.Join(" ", name.Where(n => !String.IsNullOrEmpty(n)));
}
}
}
我想创建一个视图模型的PagedList如下:
public class PersonSearch
{
public int PersonId { get; set; }
public string Name { get; set; }
}
做这件事最有效的方法是什么?
我不能使用下面的,因为它给了我一个错误的名字,这是预期的
var model = db.person.OrderBy(p => p.Surname)
.ThenBy(p => p.FirstName)
.Select(p => new PersonSearch
{
PersonId = p.PersonId,
Name = p.Name
})
.ToPagedList(page, 25);
在LINQ to Entities中不支持指定的类型成员'Name'
下面的操作可以工作,但是它首先会覆盖整个列表中的人:
var model = db.person.OrderBy(p => p.Surname)
.ThenBy(p => p.FirstName)
.ToList()
.Select(p => new PersonSearch
{
PersonId = p.PersonId,
Name = p.Name
})
.ToPagedList(page, 25);
下面的代码不起作用,因为它删除了分页信息:
var model = db.person.OrderBy(p => p.Surname)
.ThenBy(p => p.FirstName)
.ToPagedList(page, 25);
.Select(p => new PersonSearch
{
PersonId = p.PersonId,
Name = p.Name
})
.ToPagedList(page, 25);
添加一个构造函数到您的PersonSearch
模型,以便您可以生成全名
public class PersonSearch
{
public PersonSearch()
{
}
public PersonSearch(string first, string middle, string last)
{
// format and remove leading or trailing white space as a result of nulls
string name = string.Format("{0} {1} {2}", first, middle, last).Trim();
// remove any internal extra white space if middle is null
if (string.IsNullOrWhiteSpace(middle))
{
name = String.Join(" ", name.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries));
}
Name = name;
}
public int PersonId { get; set; }
public string Name { get; set; }
}
然后在查询中使用
var model = db.person.OrderBy(p => p.Surname).ThenBy(p => p.FirstName)
.Select(p => new PersonSearch(p.FirstName, p.MiddleNames, p.Surname)
{
PersonId = p.PersonId
}).ToPagedList(page, 25);