【问题标题】:How to map data from database with Griffin-Framework Data-Mapper如何使用 Griffin-Framework Data-Mapper 映射数据库中的数据
【发布时间】:2017-01-27 20:37:23
【问题描述】:

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

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

【问题讨论】:

    标签: c# sql-server mapper


    【解决方案1】:

    我对 Griffin 本身并不熟悉,但很明显问题在于您有两个单独的 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");
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-05-12
      • 2023-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多