【问题标题】:How to insert DbGeography to SQL Server using dapper如何使用 dapper 将 DbGeography 插入 SQL Server
【发布时间】:2014-08-15 15:32:50
【问题描述】:

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

【问题讨论】:

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


    【解决方案1】:

    为核心 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

    【讨论】:

    猜你喜欢
    • 2020-10-02
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多