Using Dapper-dot-net, how do I map SQL uniqueidentifier column to a .Net type?

六眼飞鱼酱① 提交于 2019-12-10 01:42:58

问题


I have an existing database that uses the SQL "uniqueidentifier" type, which looks like a different GUID format than a .Net GUID.

Question: Using Dapper, how do I map SQL uniqueidentifier column to .Net?

Issue: Using Dapper-dot-net, when I map the column using the .Net GUID type, it compiles and runs, but all of the .ToString() output displays the same incorrect GUID. (well it doesn't match what I see in SSMS)

When I try to map the column using the string type, I get a compiler error.

Ideas? Is this possible?


回答1:


I also found that I could cast it to a varchar in T-SQL, but I wanted the actual GUID type in .NET.

With Dapper 1.38 (also using SQL Server as the underlying RDBMS), I had no trouble with mapping if I made the POCO property a Nullable<Guid>. A SqlGuid or a String did not work.

public class MapMe
{
    public Guid? GuidByDapper { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        using (var connection = Utility.GetConnection())
        {
            var mapped = connection.Query<MapMe>("SELECT NEWID() AS GuidByDapper").Single();
            Console.WriteLine("Guid: {0}", mapped.GuidByDapper);
        }
    }
}

As a Console app it spits out the following:

Guid: 85d17a50-4122-44ee-a118-2a6da2a45461



回答2:


Aha! It appears that you must convert the SQL uniqueidentifier to a string in T-SQL and then map to to a string type in .Net.

string sql = @"SELECT TOP 100
               CONVERT(varchar(36), MyIdColumn) AS IdColumnString
               FROM MyTable";

conn.Query<string>(sql).ToList();

I assume special care would need to be taken converting back from .Net string to T-SQL uniqueidentifier on updates, but I have not yet tested that concern.



来源:https://stackoverflow.com/questions/20685800/using-dapper-dot-net-how-do-i-map-sql-uniqueidentifier-column-to-a-net-type

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