考虑以下几点:列表里面的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