考慮以下幾點:列表裏面的IQueryable對象
public class Person
{
public int ID { get; set;}
public string Name { get; set;}
public IQueryable<Pet> Pets { get;set; }
}
public class Pet
{
public int id { get; set; }
public int OwnerId { get; set; }
public string Name { get; set; }
}
public class SearchCriteria
{
public string PersonName {get; set; }
public List<string> PetNames {get; set;}
}
實現全選的人與他們的寵物,同時用一個IQueryable
public List<Person> GetWithPets(SearchCriteria search)
{
var people = (from p in context.People
where p.Name == search.PersonName
select new Person{
ID = p.ID,
Name = p.Name,
Pets = (from pt in context.Pets
where pt.OwnerId == p.ID
select new Pet {
id = pt.ID,
OwnerId = pt.OwnerId,
Name = pt.Name
}).AsQueryable
}).AsQueryable();
foreach(var str in search.PetNames)
{
people = people.Where(o=>o.Pets.Any(p=>p.Name == str));
}
return people.ToList();
}
我的問題搜索是,不管在foreach的,其搜索名,在返回人名單,寵物爲null即使有 那個人,我有沒有哪裏出了錯相關寵物嗎?
編輯:
public class Person
{
public int ID { get; set; }
public string Name { get; set; }
public IQueryable<Animal> Pets { get; set; }
}
public class Animal
{
public int id { get; set; }
public int? OwnerId { get; set; }
public string Name { get; set; }
}
public class SearchCriteria
{
public string PersonName { get; set; }
public List<string> PetNames { get; set; }
}
class Program
{
public static List<Person> GetWithPets(SearchCriteria search)
{
using (DatabaseEntities context = new DatabaseEntities())
{
var people = (from p in context.Peoples
where p.Name == search.PersonName
select new Person
{
ID = p.ID,
Name = p.Name,
Pets = (from pt in context.Pets
where pt.OwnerID == p.ID
select new Animal
{
id = pt.ID,
OwnerId = pt.OwnerID,
Name = pt.Name
}).AsQueryable()
}).AsQueryable();
foreach (var str in search.PetNames)
{
people = people.Where(o => o.Pets.Any(p => p.Name == str));
}
return people.ToList();
}
}
你有什麼方法咋辦回來?用'Name'等於'search.PersonName',並使用具有名稱是在'search.PetNames'任何寵物的人的名單? – Bazzz 2012-04-04 11:02:46
我的方法是應該返回具有名稱等於search.PersonName與他們所有的寵物,但只有那些誰擁有與在search.PetNames – 2012-04-04 11:09:21
這些名字的寵物是人的人員名單'Person'和'Pet'實體映射到數據庫還是他們只有助手類來獲得搜索結果?如果你刪除了'foreach'循環會發生什麼? 'Pets'仍然是'null'嗎? – Slauma 2012-04-04 11:35:31