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

有些话、适合烂在心里 提交于 2021-01-28 23:59:13

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!