如何使用dapper将DbGeography插入SQL Server

本文关键字:插入 SQL Server DbGeography 何使用 dapper | 更新日期: 2023-09-27 18:10:15

我已经创建了模型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

我试着寻找插入的方法,这是我能找到的最好的方法,但它只插入了一个参数,我应该怎么做才能插入一个有dbgeographic成员的对象?

更新#1

我已经放弃了尝试破解或扩展东西,因为我是一个衣冠楚楚的新手,时间不在我这边。我回到了基本的做法,因为我不需要频繁地插入地理数据类型

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
            });             
        }

如何使用dapper将DbGeography插入SQL Server

添加对核心ADO.NET程序集之外的类型的直接支持是有问题的,因为它要么强制进行大量基于名称的反射,要么增加依赖关系(并导致版本控制问题(。这里不需要(甚至不适合(使用IDynamicParameters——相反,ICustomQueryParameter可以用于表示单个参数。DbGeography没有现有的特殊情况检测,因此除非有库更改,否则您必须执行以下操作:

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

其中CCD_ 6是返回适当添加它的CCD_ 7实现的扩展方法。


编辑:有关以下内容的更新,请参阅此处:https://stackoverflow.com/a/24408529/23354