如何使用Griffin-Framework Data-Mapper映射数据库中的数据

时间:2016-09-20 03:34:22

标签: c# sql-server mapper

我有两张桌子: 用户和用户类型:

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进行映射

1 个答案:

答案 0 :(得分:0)

我对Griffin本身并不熟悉,但很明显,问题在于UserType有两个单独的映射。每个映射都会创建一个全新的对象,覆盖UserType对象上的User成员。根据首先映射的列,您将始终获得只有一个属性集的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");
    }
}