问题
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.
回答1:
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.
来源:https://stackoverflow.com/questions/60809569/how-to-get-entity-by-unique-key-using-dapper-contrib