2016-09-20 211 views
2

我有兩個表: 用戶和用戶類型:如何從格里芬的框架數據映射數據庫映射數據

CREATE TABLE [dbo].[User](
    [Id] [int] IDENTITY(1,1) NOT NULL, 
    [Name] [nvarchar](50) NULL, 
    [UserTypeId] [int] NOT NULL 
) 
CREATE TABLE [dbo].[UserType](
    [Id] [int] IDENTITY(1,1) NOT NULL, 
    [Name] [nvarchar](50) NULL 
) 

我的模型類:

public class User 
{ 
    public int Id { get; set; } 
    public string Name { get; set; } 
    public UserType UserType { get; set; } 
} 
public class UserType 
{ 
    public int Id { get; set; } 
    public string Name { get; set; } 
} 

我的查詢:

SELECT 
    U.Id 
    , U.Name 
    , UT.Id AS [UserTypeId] 
    , UT.Name AS [UserTypeName] 
FROM dbo.User AS F 
    INNER JOIN dbo.UserType AS UT ON U.UserTypeId = UT.Id 
ORDER BY U.Id 

而我的映射器類:

public class UserMapper : CrudEntityMapper<User> 
{ 
    public UserMapper() : base("User") 
    { 
     Property(x => x.UserType) 
      .ColumnName("UserTypeId") 
      .ToPropertyValue((x) => new UserType { Id = (int)x }); 
     Property(x => x.UserType) 
      .ColumnName("UserTypeName") 
      .ToPropertyValue((x) => new UserType { Name = (string)x }); 
    } 
} 

當我嘗試執行命令時,我得到沒有userType.Id的用戶列表(Id總是= 0)。我需要填寫我的User和子類UserType的數據。

請告訴我我做錯了什麼。

cmd.ToList<User>(); 

PS。即時通訊使用Griffin.Framework進行映射

回答

0

我對格里芬本身並不熟悉,但很明顯,問題在於您有兩個單獨的UserType映射。每個映射都會創建一個全新對象,用於覆蓋User對象上的UserType成員。根據首先映射哪個列,您將始終獲得僅具有一個屬性集的UserType對象。

看看FluentPropertyMapping的來源,似乎沒有選項可將多個列映射到一個。潛在的解決方法,這取決於支持映射嵌套的屬性:

public class User 
{ 
    public User() 
    { 
     UserType = new UserType(); 
    } 

    public int Id { get; set; } 
    public string Name { get; set; } 
    public UserType UserType { get; set; } 
} 

,並在你的映射:

public class UserMapper : CrudEntityMapper<User> 
{ 
    public UserMapper() : base("User") 
    { 
     Property(x => x.UserType.Id) 
      .ColumnName("UserTypeId"); 
     Property(x => x.UserType.Name) 
      .ColumnName("UserTypeName"); 
    } 
}