2015-10-11 23 views
1

這是我的框架,通過的EntityFramework 6發展:實體框架6產生額外加入時發送查詢爲sql

用戶的DataModel:

[DataContract] 
[Table("SEC_User")] 
public class UserDataModel : EntityBase 
{ 
    [DataMember] 
    [Key] 
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)] 
    [Column("UserID")] 
    public int UserID{get;set;} 

    [DataMember] 
    [Column("UserName")] 
    public string UserName{get;set;} 

    [DataMember] 
    [Column("UserKindRef")] 
    public int UserKindRef{get;set;} 
    . 
    . 
    . 
} 
[DataContract] 
[Table("SEC_User_View")] 
public class UserViewDataModel : UserDataModel 
{ 
    [DataMember] 
    [Column("UserKindTitle")] 
    public string UserKindTitle{get;set;}   
} 

數據訪問方法:

public UserViewDataModel GetByUserName(string userName) 
    { 
     using (Context) 
     { 
     return (from entity in Context.EntityList 
       where entity.UserName == userName 
       select entity).FirstOrDefault().ToEntity(); 
     } 
    } 

SQL事件探查器:

exec sp_executesql N'SELECT 
[Limit1].[C1] AS [C1], 
[Limit1].[UserID] AS [UserID], 
[Limit1].[UserName] AS [UserName], 
[Limit1].[UserKindRef] AS [UserKindRef], 
[Limit1].[UserKindTitle] AS [UserKindTitle] 
FROM (SELECT TOP (1) 
    [Extent1].[UserKindTitle] AS [UserKindTitle], 
    [Extent2].[UserID] AS [UserID], 
    [Extent2].[UserName] AS [UserName], 
    [Extent2].[UserKindRef] AS [UserKindRef], 
    ''0X0X'' AS [C1] 
    FROM [dbo].[SEC_User_View] AS [Extent1] 
    INNER JOIN [dbo].[SEC_User] AS [Extent2] ON [Extent1].[UserKey] =[Extent2].[UserKey] 
    WHERE ([Extent2].[UserName] = @p__linq__0) OR (([Extent2].[UserName] IS NULL) AND (@p__linq__0 IS NULL)) 
) AS [Limit1]',N'@p__linq__0 nvarchar(4000)',@p__linq__0=N'admin' 

不幸的是,當UserViweDataModel從UserDataModel實體框架繼承時,entityframework使用select來選擇並將SEC_User_View連接到SEC_User,這是錯誤的。 它應該是這樣的:

exec sp_executesql N'SELECT TOP (1) 
[Extent1].[UserID] AS [UserID], 
[Extent1].[UserName] AS [UserName], 
[Extent1].[UserKindRef] AS [UserKindRef], 
[Extent1].[UserKindTitle] AS [UserKindTitle] 
FROM [dbo].[SEC_User_View] AS [Extent1] 
WHERE ([Extent1].[UserName] = @p__linq__0) OR (([Extent1].[UserName] IS NULL) AND (@p__linq__0 IS NULL))',N'@p__linq__0 nvarchar(4000)',@p__linq__0=N'admin' 

什麼是我的錯????

+1

你想做什麼?你爲什麼需要繼承?這兩個類都有一個表和獨特的屬性,所以EF不知道所有在'SEC_User_View'爲什麼你需要這樣的基類?只需將所有屬性放在'SEC_User_View' –

+0

@EricKelly:首先,這是我的標準框架,可以在所有項目上執行。另一點實體框架在視圖上使用第一個表作爲主數據,並在第一個表上保存更改(我希望我理解正確),但有時第一個表不是主要的。我必須分開tablemodel和viewmodel。用於保存更改的表模型和用於選擇的視圖模型。也有些時候表現不是必要的使用視圖選擇列表... – amin

回答

0

Table(SEC_User)Table(SEC_User_View)。你告訴 EF你想要兩張桌子。

Inheritance with EF: Table Per Hierarchy

爲EF默認爲TPH,但–用Table –裝飾兩個類你告訴它你想TPT(請參閱博客文章中,我上面貼的第2部分)。

順便說一句,如果你確實想要TPH –這聽起來像你做–一個和唯一的表將會是基類,而不是派生。