2012-03-06 326 views
1

我有以下型號:繼承和LINQ到實體

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

結果懶惰加載讓我。需要使用Include()來包含我需要加載的屬性。 – khaihon 2012-03-08 22:57:23

回答

0

試試這個:

var studentIds = rider.OfType<Student>().Select(x => x.studentId); 
+0

OfType在Linq to Entities中受支持:http://msdn.microsoft.com/en-us/library/bb738551.aspx – avs099 2012-03-06 21:58:13

+0

很好的參考,謝謝 – 2012-03-06 23:51:00

0

如果你的代碼是你顯示什麼,這將工作:

學童校車=新校車();

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上,你應該顯示你的確切代碼和你的問題。