2016-02-11 60 views
0

我有一個使用數據庫第一種方法生成的實體框架設置。其中我有一個用戶表和一個配置文件表。如何指示實體框架選擇兩個表之間具有多個外鍵的正確關係?

User 
- UserId 
- ProfileId 

Profile 
- ProfileId 
- {unimportant profile details} 
- ModifiedOn 
- CreatedOn 

在這些表中的每個表中,它們是主鍵。問題是這兩個表之間有3個外鍵關係。

  1. 用戶已經
  2. 創建配置文件由用戶A簡檔(User.FK_User_Profile User.ProfileId == Profile.ProfileId)(Profile.FK_UserCreatedBy Profile.CreatedBy == User.UserId)
  3. 一個配置文件被用戶修改(Profile.FK_UserModifiedBy Profile.ModifiedBy == User.UserId)

這一切都可以在數據庫中正常工作。不幸的是,當我嘗試訪問具有以下Linq查詢從該所產生的EDMX:

databaseContext.User.Where(u => u.UserID == SOMEGUID) 
      .Select(p => p.Profile.FirstOrDefault()) 

生成的SQL是這樣的:

SELECT projected details 
    FROM (SELECT 
    [Extent1].UserId as UserId, 
    [Extent2].ProfileId as ProfileId, 
    [Other fields], 
    FROM [dbo].[User] AS [Extent1] 
    LEFT OUTER JOIN [dbo].[Profile] AS [Extent2] ON *[Extent1].[UserID] = [Extent2].[ModifiedBy]* 
    WHERE [Extent1].[ProfileID] = efGeneratedId 
) AS [Project1] 

的問題是左外連接標準。相反,在

Extent1.UserId = Extent2.ModifiedBy 

加入上

Extent1.UserId = Extent2.UserId 

它的加盟這導致的LINQ檢索其修改配置文件,而不是用戶具有配置文件的所有用戶。

如何指示EF映射此查詢或更可能這些關係正確?

+0

你能添加類用戶的定義和資料收集?你在屬性中使用了什麼屬性? –

+0

請顯示edmx生成。如果用戶有1個配置文件,那麼您正在使用的導航屬性是錯誤的,因爲您正在做firstordefault,而不是用於導航屬性的collection(我的意思是Profile prop是一個集合,所以它代表了1:N配置文件到用戶關係之一) – tede24

回答

1

由於您沒有包含有關生成EDMX任何信息,我會盡量想..: 這些表的模型應該產生像這樣的用戶等級:

int ProfileId {get; set;} 
Profile Profile {get; set;} //->An user has A profile 
ICollection<Profile> ProfileX {get; set;} //CreatedBy 
ICollection<Profile> ProfileY {get; set;} //ModifiedBy 

根據SQL你發佈了,你的linq的「Profile.FirstOrDefault」是我的示例的「ProfileY」集合。

你應該調整EDMX屬性命名,並使用一個代表用戶配置文件的關係,這不應該是

+0

您指引我朝着正確的方向前進。 edmx確實生成了Profile,Profile1和Profile2。如預期的那樣,不是使用FK_User_Profile鍵進行配置文件,而是使用FK_Profile_UserModified_By鍵。 Profile1正在使用正確的FK_User_Profile項。謝謝。 – Necoras

相關問題