如何使用Dapper.Contrib通过唯一键获取实体? [英] How to Get entity by Unique Key using Dapper.Contrib?
问题描述
我有一个对象,假设
public class User
{
[Key]
int TheId { get; set; }
string Name { get; set; }
int Age { get; set; }
}
TheId
是我的自动增量列,而 Name
是我的唯一键.保存用户时,我想通过以下方式检查其存在:
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");
但是,由于我的密钥不是 Name
,而是 TheId
,因此我无法执行此操作.如果我将 Name
属性设置为 [KeyExplicit]
,那么我想通过以下方式保存用户:
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);
这一次,精打细算的人希望我填写 TheId
属性,而不是让数据库自动递增.
This time, dapper expect TheId
property filled by me, not let database to auto increment.
因此,我想知道是否有一种优雅的方法可以实现在db上搜索时将一些属性标记为精简版要考虑的属性.我不想按 Guid
进行搜索,而是按唯一键进行搜索.
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.
推荐答案
If I understood correctly, you are willing to Get
by property other than key.
dapper-contrib不支持此功能.对于 Get
,您应仅使用键字段.即使该其他属性是唯一键,也是不可能的.您所做的任何其他调整(在 Name
属性上设置 [KeyExplicit]
)都不是解决此问题的正确方法.如您所见,它还会产生其他问题.
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.
对于具有其他属性的 Get
,更好的选择是直接绕过Contrib使用Dapper.
For Get
with other properties, better alternative is to use Dapper directly bypassing Contrib.
这篇关于如何使用Dapper.Contrib通过唯一键获取实体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!