使用 Dapper ORM 的最简单方法

Easiest way to use Dapper ORM

将 Dapper ORM 查询的输出放入提供查询方法的 class 的数据成员中的最简单方法是什么?

这是我的代码,方法 A(丑陋)和方法 B(不起作用):

public class MyLab_ClientRef
{
    public int UserId { get; set; }
    public string ClientId { get; set; }
    // ... more fields ...

    public bool GetUser(OracleConnection conn, int UserId, string ClientId)
    {
        bool Ok = false;
        IEnumerable<MyLab_ClientRef> QueryResultRecords =
            conn.Query<MyLab_ClientRef>(@"
                SELECT *
                FROM MyLab_ClientRef
                WHERE UserId   = :UserId
                  AND ClientId = :ClientId",
            new { UserId = UserId, ClientId = ClientId });
        if (QueryResultRecords.Count() == 1)
        {
            // Method A
            MyLab_ClientRef Rec = QueryResultRecords.First(); // works
            CopyRec(Rec, this);                               // ugly

            // Method B
            this = QueryResultRecords.First();            // avoids CopyRec, does not work

            Ok = true;
        }
        return Ok;
    }

    private static void CopyRec(MyLab_ClientRef CR_From, MyLab_ClientRef CR_To)
    {
        CR_To.UserId = CR_From.UserId;
        CR_To.ClientId = CR_From.ClientId;
    }
}

我喜欢让记录定义靠近获取记录的查询,但不喜欢用这种方式为每个 table class 实现一个 CopyRec 方法。

有没有更好的实现方式?我试着写 this = ... 但那是不可能的。

如何写出比方法A更好的方法B?

以下内容无效:

this = QueryResultRecords.First();

检查以下 link 的原因:

Why can't I set "this" to a value in C#?

MSDN

如上面第一个 link 所示,您最好的选择仍然是您 return 来自给定方法的 MyLab_ClientRef,可以将其设为静态并使用 if for value or reference 赋值,在这种情况下,两者都应该产生相同的结果

如果在您看来这是一个更清晰的实施,请检查以下内容:

public class MyLab_ClientRef
{
    public int UserId { get; set; }
    public string ClientId { get; set; }
    // ... more fields ...

    public static MyLab_ClientRef GetUser(OracleConnection conn, int UserId, string ClientId)
    {
        bool Ok = false;

        var QueryResultRecords =
            conn.Query<MyLab_ClientRef>(@"SELECT * FROM MyLab_ClientRef WHERE UserId = :UserId AND ClientId = :ClientId",new { UserId = UserId, ClientId = ClientId });

            if(QueryResultRecords.Any())
                return QueryResultRecords.First();
            else
                return null;        

    }  
}

可以这样称呼:

var newClient = MyLab_ClientRef.GetUser(conn, UserId,ClientId);

尽管 connection 对象是方法的本地对象并且在 using 时钟中使用