在小巧玲珑的映射实体 [英] Mapping entity in Dapper
问题描述
我刚开始与小巧玲珑的工作,我似乎还没有找到的东西很简单,就像在我的数据库实体映射到一个表:
I've just started working with Dapper and I don't seem to find something very simple like mapping an entity to a table in my database:
我有一个存储过程:
CREATE PROCEDURE [dbo].GetUserById (@UserId int)
AS
begin
SELECT UserId,LastName,FirstName,EmailAddress
FROM users
WHERE UserID = @UserId
end
go
然后一个实体:
Then an entity:
public class User
{
public int Id { get; set; }
public string LastName { get; set; }
public string FirstName { get; set; }
public string Email { get; set; }
}
和我的code短小精悍查询:
And a dapper query in my code:
int userid=1;
User User = connection.Query<User>("#GetUserById", new {userid=userid}, commandType: CommandType.StoredProcedure).FirstOrDefault();
我的问题是:我怎样才能知道我的实体网友认为标识是用户ID对我的数据库
My question is: How can I tell my entity User that Id is Userid on my database?
在EF,我会做这样的事情:
In EF I would do something like this:
MapSingleType(c => new
{
UserId = c.Id,
Firstname = c.Firstname,
Lastname = c.Lastname,
EmailAddress = c.Email
}).ToTable("users");
如何能在上面短小精悍的实现?
How can the above be achieved in dapper?
推荐答案
小巧玲珑的故意不具有映射层;这是绝对最低,可以工作,并坦言覆盖了绝大多数的真实场景的过程中。不过,如果我理解正确的话,你不希望在TSQL别名,并且不希望任何直通属性 - 然后使用非通用查询
API
Dapper deliberately doesn't have a mapping layer; it is the absolute minimum that can work, and frankly covers the majority of real scenarios in the process. However, if I understand correctly that you don't want to alias in the TSQL, and don't want any pass-thru properties - then use the non-generic Query
API:
User user = connection.Query("...", ...).Select(obj => new User {
Id = (int) obj.UserId,
FirstName = (string) obj.FirstName,
LastName = (string) obj.LastName,
Email = (string) obj.EmailAddress
}).FirstOrDefault();
或者更简单地在一个记录的情况下:
or perhaps more simply in the case of a single record:
var obj = connection.Query("...", ...).FirstOrDefault();
User user = new User {
Id = (int) obj.UserId,
FirstName = (string) obj.FirstName,
LastName = (string) obj.LastName,
Email = (string) obj.EmailAddress
};
这里的窍门是,非通用查询(...)
API使用动态
,提供高达每列名成员。
The trick here is that the non-generic Query(...)
API uses dynamic
, offering up members per column name.
这篇关于在小巧玲珑的映射实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!