2013-05-01 102 views
0

我關於實施EF反對到它的參與者,包括教師如下鏈接培訓班現有的數據庫工作創建1-1導航屬性從1一對多的關係

Training 
------------------- 
ClassId (PK) 

TrainingParticipant 
------------------- 
ParticipantId (PK) 
ClassId (FK references Training) 
PersonId (FK references Person) 
ParticipantRoleId (FK references a role table) 

的參與者表應該有1-10名參與者和1名培訓師。 (以其ParticipantRoleId來區分)。我已經開始進行數據庫優先開發,並生成了映射培訓和培訓參與者之間一對多關係的edmx和上下文/模型;但是,它生成的導航屬性將帶回所有TrainingParticipant條目的集合。

我不斷地編碼類似下面的查詢來檢查,或獲取記錄的單教練員參加像這樣:

var trainer = context.TrainingParticipant.Where(p => p.ParticipantRoleId == 17).FirstOrDefault() 

var students = context.TrainingParticipant.Where(p => p.ParticipantRoleId == 2) 

我會非常想有一個導航屬性,這將使訪問這些在複雜的查詢中以及將模型數據綁定到UI時更直接。像這樣:

var training = context.Training.Where(t => t.Instructor.Person.FirstName.Contains("John")); 

是否有可能創建這樣的導航屬性,最好不改變任何表?

回答

0

什麼關於你的EF實體創建一個新的getter方法返回這個新屬性只是返回這個值

public class MyEntity{ 
    public int Id {get;set;} 
    public ICollection<OtherThing> Things {get;set;} 
    [NotMapped] 
    public OtherThing TheOneRealThing 
    { 
     get 
     { 
      return Things.First(); 
     } 
    } 
} 

它不是一個「真正」的導航屬性,但對於您的應用程序也可能會做出你會期待。

+0

@ user2337991嗯有趣的是,我不是100%肯定如果您首先通過帶有DB的部分包含屬性,該如何忽略該屬性。如果[未映射]註釋不起作用,我不太確定你是如何做到這一點的。我會有一些想法,或者如果有人知道我好奇 – 2013-05-01 02:57:27