2
votes

I have two tables: User and UserType:

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
)

My model classes:

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; }
}

My query:

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

And my mapper class:

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 });
    }
}

when i try to execute command i get list of users without userType.Id (Id always = 0). I need to fill with data my User and child UserType classes.

Please show me what i'm doing wrong.

cmd.ToList<User>();

PS. im using Griffin.Framework for mapping

1

1 Answers

0
votes

I'm not familiar with Griffin per se, but it's clear the issue is the fact that you have two separate mappings for UserType. Each mapping is creating a brand new object that overwrites the UserType member on your User object. Depending on which column gets mapped first, you'll always get a UserType object that has only one property set.

Looking at the source for FluentPropertyMapping, there does not appear to be an option to map multiple columns down to one. A potential workaround, which depends on support for mapping nested properties:

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

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

and in your mapping:

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