c# - 如何使用 dapper 将 DbGeography 插入 SQL Server

标签 c# sql-server geospatial dapper micro-orm

我创建了模型using System.Data.Entity.Spatial;

public class Store
{
    public int Id { get; private set; }
    public string Name { get; set; }
    public string Address { get; set; }
    public DbGeography Location { get; set; }
}

插入数据库

using (SqlConnection conn = SqlHelper.GetOpenConnection())
{
    const string sql = "INSERT INTO Stores(Name, Address, Location) " + 
                       "VALUES (@Name, @Address, @Location)";
    return conn.Execute(sql, store);                                
}

我得到异常 type System.Data.Entity.Spatial.DbGeography cannot be used as a parameter value

我试过寻找插入的方法,this是我能找到的最好的,但它试图只插入 1 个参数,我应该怎么做才能插入具有 dbgeography 成员的对象?

更新 #1

我已经放弃尝试破解或扩展东西,因为我对 dapper 还很陌生,而且目前时间不在我这边。我回到基本的做法,因为我不需要非常频繁地插入地理数据类型

using (SqlConnection conn = SqlHelper.GetOpenConnection())
        {
            var sql = "INSERT INTO Stores (Name, Address, IsActive, Location, TenantId) " +
                      "VALUES('@Name', '@Address', @IsActive, geography::Point(@Lat,@Lng, 4326), @TenantId);";

            return conn.Execute(sql, new 
            { 
                Name = store.Name, 
                Address = store.Address, 
                IsActive = store.IsActive,
                Lat = store.Location.Latitude.Value,
                Lng = store.Location.Longitude.Value,
                TenantId = store.TenantId
            });             
        }

最佳答案

在核心 ADO.NET 程序集之外添加对类型的直接支持是有问题的,因为它要么强制进行大量基于名称的反射,要么增加依赖性(并导致版本控制问题)。在此处使用 IDynamicParameters 是没有必要的(或者甚至是适当的,IMO)- 相反,ICustomQueryParameter 可用于表示单个参数。没有现成的 DbGeography 特例检测,所以除非库发生变化,否则您必须执行如下操作:

return conn.Execute(sql, new {
    store.Name, store.Address, Location=store.Location.AsParameter()
});

其中 AsParameter() 是一个扩展方法,它返回一个适当添加它的 ICustomQueryParameter 实现。


编辑:请参阅此处了解更新:https://stackoverflow.com/a/24408529/23354

关于c# - 如何使用 dapper 将 DbGeography 插入 SQL Server,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24402424/

相关文章:

SQL Express 2005/2008 并发连接

SQL Server 循环删除记录超出锁定超时

sql-server - 地理空间支持,SQL Server 08 vs MongoDB?

python - 来自一组坐标的边界点

c# - 子 web.config 是否有忽略父 web.config 的命令或设置

c# - 如何在我的连接字符串上使用 Web.Config 转换?

sql-server - 无法在 Visual Studio 2012 或 2013 中打开 SSIS 项目(迁移失败)

mysql - MySQL 查询中两个空间点之间的距离(以米为单位)

javascript - Asp.Net Core + Angularjs2,在一起还是分开?

c# - 用户控制回传