我有一个小问题需要帮助解决:
我有以下情况:
例如:我想选择所有有狗的学生。
我有 2 个表:
students
id name petid
pet
id name
但是它们之间没有指定的外键没有导航属性,虽然我有但我没有指定它并且我不想要我的情况,但我仍然想做出正确的选择语句。
所以有了导航属性我可以这样查询:
var students = (student s in context.students where s.Pet.Name.Equals("dog").ToList();
我也会避免这样做
var students = context.students
foreach(student s in students)
{
string pet = (from pet p in context.pets where p.Id==s.PetId select p.name).SingleOrDefault();
if(pet=="dog")
{
//do something
}
}
当然,制作导航属性很容易,但就我而言,我真的不想这样做。
所以我的问题是我怎样才能简单地进行这种查询,并且只需要一个数据库?
最佳答案
使用联接。
var students = (from s in context.students
join p in context.pets on s.petid equals p.id
where p.name == "dog"
select s).ToList();
对于 lambda 语法,你可以使用这个:
var students = context.students.Join(context.pets.Where(p => p.name== "dog"), //filter the pets
student => student.PetId, //left side key for the join
pet => pet.id, //right side key for the join
(student, pet) => student); //what do you want to select
关于c# - EF 6 从没有导航属性的其他表中选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21535248/