鉴于以下内容:
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();
}
}
答案 0 :(得分:2)
如果 Person
和Pet
是模型的实体,如果 Person.Pets
是{{1}的导航属性实体和如果您想拥有包含所有完整Pet
实体的完整Person
实体,并引用您的评论......
我的方法应该返回名称相等的人员列表 search.PersonName&amp;他们所有的宠物,但只有那些拥有它的人 在search.PetNames
中有这些名字的宠物
......你可以用这个:
Pet
答案 1 :(得分:0)
你可以试试这样的事吗
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
})
}).Include("Pets").AsQueryable();
答案 2 :(得分:0)
或者你可以试试这样的东西
foreach(var str in search.PetNames)
{
people.Concat(people.Where(o=>o.Pets.Any(p=>p == str)).Include('Pet'));
}
答案 3 :(得分:0)
将AsQueryable()
添加到Pets
集合:
Pets = (from pt in context.Pets
where pt.OwnerId == p.ID
select new Pet {
id = pt.ID,
OwnerId = pt.OwnerId,
Name = pt.Name
}).AsQuerable()