I would like to get the list of users from the database, but I want only 5 columns instead of all (it has about 35 columns). When I wrote like the following, it shows me no error at the compile time but the error at the runtime.
我想从数据库中获取用户列表,但是我只需要5列,而不是全部(它大约有35列)。当我像下面这样写时,它在编译时显示的不是错误,而是运行时的错误。
bksb_Users is the table name in my database as well as object name in the Entity Model.
bksb_Users是我的数据库中的表名,以及实体模型中的对象名称。
public List<bksb_Users> SearchStudents(string reference, string firstname, string lastname)
{
return (from u in context.bksb_Users
where u.userName.Contains(reference)
&& u.FirstName.Contains(firstname)
&& u.LastName.Contains(lastname)
orderby u.FirstName, u.LastName
select new bksb_Users
{
user_id = u.user_id,
userName = u.userName,
FirstName = u.FirstName,
LastName = u.LastName,
DOB = u.DOB
}).Take(100).ToList<bksb_Users>();
}
The error is...
这个错误是……
The entity or complex type 'bksbModel.bksb_Users' cannot be constructed in a LINQ to Entities query.
3
Does below work?
下面的工作吗?
public List<bksb_Users> SearchStudents(string reference, string firstname, string lastname)
{
var anon = (from u in context.bksb_Users
where u.userName.Contains(reference)
&& u.FirstName.Contains(firstname)
&& u.LastName.Contains(lastname)
orderby u.FirstName, u.LastName
select new
{
user_id = u.user_id,
userName = u.userName,
FirstName = u.FirstName,
LastName = u.LastName,
DOB = u.DOB
}).Take(100).ToList();
return anon.Select(z => new bksb_Users()
{
user_id = z.user_id, userName = z.userName, FirstName = z.FirstName, DOB = z.DOB
}).ToList();
}
All I have done is split the task into two steps:
我所做的就是把任务分成两个步骤:
Note a better option would be to create a new type (class) that contains just the fields/properties you need - that would remove the need for step 2, and will make it clear to the callers of your function which columns are 'populated' and which aren't. It also means you are less likely to 'accidentally' try and persist these half populated entities back to the database.
注意,一个更好的选择是创建一个新类型(类),其中只包含您需要的字段/属性——这将消除第2步的需要,并向函数的调用者表明哪些列是“填充的”,哪些列不是。这也意味着您不太可能“偶然”尝试并将这些半填充的实体保存到数据库中。
0
for some reason i quess that field DOB looks something like this
出于某种原因,我认为场DOB是这样的
public object DOB { get { return fieldX + fieldY } }
Entity framework does not understand that. All fields in query must be mapped with certain columns in DB
实体框架不理解这一点。查询中的所有字段必须与DB中的某些列进行映射
本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.silva-art.net/blog/2011/11/28/7dfa1b1cfcdd59fe7b0e61cae6d226d9.html。