tmsmith / Dapper-Extensions

Dapper Extensions is a small library that complements Dapper by adding basic CRUD operations (Get, Insert, Update, Delete) for your POCOs. For more advanced querying scenarios, Dapper Extensions provides a predicate system. The goal of this library is to keep your POCOs pure by not requiring any attributes or base class inheritance.
1.79k stars 586 forks source link

ReferenceMap not mapping correctly #279

Open abhilashca opened 2 years ago

abhilashca commented 2 years ago

Hello,

I integrated Dapper.Extensions into an existing project recently. And, I was trying to map data of the child item via ReferenceMap. For some reason, it is not mapping as expected. I have gone through the test case provided but was unable to make it working.

Here is how my code snippet looks like:

// User Group Member class
public class UserGroupMember
{
    public int UserGroupMemberId { get; set; }   // Primary Key
    public int UserGroupId { get; set; }
    public int UserId { get; set; }

    // Type I am trying to map.
    public User UserInstance { get; set; }
}
// User class
public class User
{
    public int UserId { get; set; }    // Primary Key
    public string FirstName { get; set; }        
    public string LastName { get; set; }
}
// User Group Member Class Mapper
public class UserGroupMemberMapper : ClassMapper<UserGroupMember>
{
    public UserGroupMemberMapper()
    {
        TableName = "UserGroupMember";

        Map(m => m.UserInstance).Ignore();
        AutoMap();

        ReferenceMap(m => m.UserInstance).Reference<User>((u, gm) => u.UserId == gm.UserId);
    }
}

When I load group member collection, UserInstance is always returning null.

Any idea what I am missing here? Any help will be appreciated.

Thank you.

abhilashca commented 2 years ago

@valfrid-ly I have gone through the test case explaining reference map. However, I am unable to make it working. Do you have any thoughts on why it's not working?

valfrid-ly commented 2 years ago

Sorry for the delay @abhilashca , you need to also create a map to the User class, so it'll find the table.

Please test it and follow up with me.

abhilashca commented 2 years ago

Thank you @valfrid-ly. Much appreciated for the reply. Let me try the same and will keep you posted.

a-priestley commented 2 years ago

Hi again, I'm having trouble comprehending what needs to be done. Is there any way you have time to provide a fleshed-out example? I am also attempting to accomplish joins but to no avail.. Is the OP's first Mapper correct?

If so, then the second mapper could be like so:

Table("UserInstance")
AutoMap();

My example has explicit properties but the references don't resolve. If I do var mapper = await DapperAsyncExtensions.GetMap<User>();

mapper.References is empty.