[英]How to insert DbGeography to SQL Server using dapper
我using System.Data.Entity.Spatial;
創建了模型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
我已經嘗試過尋找插入的方法, 這是我能找到的最好的,但它試圖只插入一個參數,我該怎么做才能插入一個有dbgeography成員的對象?
我已經放棄了試圖破解或擴展內容,因為我對新手來說非常新,時間不在我身邊。 我回到基本這樣做,因為我不需要非常頻繁地進行地理數據類型插入
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.