我怎么能叫从一个LINQ EX pression的方法? [英] How can I call a method from within a LINQ expression?
问题描述
我有我的模型的东西,也许是这样的:
I've my Model something maybe like this :
public class Person
{
public virtual Guid ID { get; set; }
public virtual string FirstName { get; set; }
public virtual string LastName { get; set; }
//this LazyList takes IQueryable<T> in constructor
public virtual LazyList<Role> Roles { get; set; }
//this method to convert the object that comes from EF to my own model
public static Person FromData(DBPerson dbPerson)
{
if (dbPerson != null)
return new Person
{
ID = dbPerson.ID,
FirstName = dbPerson.FirstName,
LastName = dbPerson.LastName,
};
return null;
}
}
然后在我的仓库我有方法让所有的人,但我需要它给了 LazyList&LT;作用&GT;
属性将导致其他私有方法getRoles。
我的资料库看起来是这样的:
Then in my Repository I've method to get all persons but i need it to give to the LazyList<Role>
property result from other private method "getRoles".
My repository looks like this:
public IQueryable<Person> GetPersons()
{
var list = from dbPerson in context.Persons
select Person.FromData(dbPerson);
// Here is the problem :(
return list;
}
private LazyList<Role> getRoles(GUID userID)
{
var list = from role in db.Roles
where role.UserID == userID
select role.ToModel();
return new LazyList<Role>(list);
}
我想要的东西,在这里告诉大家,我想Person.Roles从getRoles法
也许会有人告诉我将转换dbPerson我的人在仓库的逻辑,然后把这样的事情:
Maybe someone will tell me to put the logic of converting the dbPerson to my Person in the repository and then put something like this :
public IQueryable<Person> GetPersons()
{
var list = from dbPerson in context.Persons
select new Person{
ID = dbPerson.ID,
FirstName = dbPerson.FirstName,
LastName = dbPerson.LastName,
Roles = getRoles(dbPerson.ID)};
}
确定,将工作,但我真的需要把转换dbPerson到我的模型在不同的方法,因为我就告了很多次,我的解决方案的逻辑。
OK that will work but i really need to put the logic of converting dbPerson to my model in separate method because i'll sue it many times in my solution.
那么怎么办呢?
推荐答案
我意识到,我不能只是以前叫我特殊的方法调用任何外部方法,直到我的GetEnumerator。 而这个错误是提出的实体框架。
I realized that i can't call any external method until i GetEnumerator just before calling my special method. And this error is raised by Entity Framework.
所以,code应该是这样的:
public IQueryable<Person> GetPersons()
{
var list = context.Persons.select(p=>p).AsEnumerable()
.Select(m=>m.MyExtensionMethod());
return list;
}
这篇关于我怎么能叫从一个LINQ EX pression的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!