Omer
Omer

Reputation: 10214

How to Get entity by Unique Key using Dapper.Contrib?

I have an object, assume

public class User
{
    [Key]
    int TheId { get; set; }
    string Name { get; set; }
    int Age { get; set; }
}

TheId is my auto increment column and Name is my unique key. When saving a user, I want to check its existence by:

var user= connection.Get<User>("John");

But, because of my Key is not Name but TheId, I can't do this. If I set Name property as [KeyExplicit] that time when I want to save my user by:

connection.Insert(myUser);

This time, dapper expect TheId property filled by me, not let database to auto increment.

So, I wonder is there an elegant way to achieve to mark some property or properties to dapper take into account while searching on db. I don't want to search by Guid but unique keys.

Upvotes: 1

Views: 1904

Answers (1)

Amit Joshi
Amit Joshi

Reputation: 16408

If I understood correctly, you are willing to Get by property other than key.

This is not supported by dapper-contrib. For Get, you should use key field only. This is not possible even if that other property is unique key. Any other adjustments you are doing (setting [KeyExplicit] on Name property) is not the proper way to handle this; it will create other problems as you can see.

For Get with other properties, better alternative is to use Dapper directly bypassing Contrib.

Upvotes: 1

Related Questions