我有以下型号:
public class Person
{
long Id;
string name;
}
public class Student : Person
{
string studentId;
}
public class Bus
{
long Id;
public ICollection<Person> riders {set; get;}
}
public class SchoolBus : Bus
{
long schoolBusNumber;
}
我还有以下代码:
SchoolBus schoolBus = new SchoolBus();
schoolBus.riders = new List<Person>
{
new Student { name = "Jim" },
new Student { name = "Jane }
}
var query = from rider in SchoolBus.riders
select new
{
(rider as Student).studentId;
}
学生和人被设置为单独的表,我正在使用DbContext。
我知道为什么这不起作用,但是有什么方法可以让我通过使用Person集合来返回正确的studentId?
答案 0 :(得分:0)
试试这个:
var studentIds = rider.OfType<Student>().Select(x => x.studentId);
答案 1 :(得分:0)
如果您的代码与您显示的完全相同,则可以使用:
SchoolBus schoolBus = new SchoolBus();
schoolBus.riders = new List<Person>
{
new Student { name = "Jim" },
new Student { name = "Jane }
}
var query = from rider in SchoolBus.riders
select new
{
riderID = (rider as Student).studentId;
}
但是如果您的查询在linq2entity上运行,您应该显示确切的代码和问题。