2011-08-25 92 views
1

我正在使用實體框架4.1。我有一個正常的模型.edmx,它將Match類映射到'Match'數據庫表,並且可以使用EF正常訪問它。實體框架部分類按ID /主鍵實例化

但是我需要匹配自定義屬性的方法,所以我擴展了這個使用部分類,我可以加我的屬性等

所有這一切工作正常,但我無法找出如何實例我的部分匹配類的一個實例,它的主鍵/ id。也就是說,我可以將Id傳遞給構造函數,並使用數據庫中的所有數據填充對象。

我知道我們可以做以下的調用代碼來填充:

public Match PopulateforMatchId(int matchId) 
    { 
     var match = (from m in _db.Matches 
         .Include("TeamA") 
         .Include("TeamB") 
         .Include("Season") 
         .Include("Season.Competition") 
        where m.Match_ID == matchId 
        select m).FirstOrDefault(); 

     return match; 

    } 

然而,這不是我所需要的,因爲這是不包含在局部類內部的自我,我需要它來填充自己,因爲部分類中的其他屬性依賴於對象本身的數據,然後才能進行計算。

任何人有任何想法我可以做到這一點?

感謝

凱文

+0

你看過'Attach'嗎? (http://msdn.microsoft.com/en-us/library/bb896271.aspx)但是,IMO聽起來像你正在接近這個錯誤的方式。最好讓ORM創建對象,然後填充空白(可能使用部分方法在實現過程中應用更改) –

+0

感謝您的這一點,我會以不同的方式處理這個問題,因爲看起來這不是繼續。 – Kevin

回答

1

這是使用實體框架錯誤的方式。實體框架不適合簡單地填充現有對象。而且它要求實體具有內部對EF環境的依賴。

如何可能使它工作(但我絕對不推薦):

public Match(int matchId) 
{ 
    // You called constructor yourselves = you have unproxied entity without 
    // dynamic change tracking and without lazy loading 

    Id = matchId; 

    // I'm not sure if this is possible in entity constructor but generally it should work 

    // Get context somewhere - service locator pattern 
    ObjectContext context = ContextProvider.GetCurrent(); 
    context.Matches.Attach(this); 
    context.Refresh(RefreshMode.StoreWins, this); 
    // Now you should have populated Match entity itself but not its navigation properties 

    // To populate relations you must call separate query for each of them because `Include` 
    // is possible only when the entity is created and loaded by EF and lazy loading is off 
    // in this case 

    context.LoadProperty(this, m => m.TeamA); 
    context.LoadProperty(this, m => m.TeamB); 

    Season = (from s in context.Seasons.Include("Competition") 
       select s).ToList();  
} 

這也是錯誤的構造函數的例子 - 構造函數不應該採取這樣的重邏輯。它應該是其他一些初始化方法的責任。

+0

感謝你們,如果它不是正確的做法,我會堅持我已經做的事情,我想檢查我沒有失去一些至關重要的東西。非常感謝您的幫助。 – Kevin