2017-10-12 139 views
1

我有一個提交頁面,其中一個窗體的字段是緯度/經度座標。我將它們存儲在一個名爲「位置」 System.Data.Entity.Spatial.DbGeography,並渲染領域是這樣的:System.Data.Entity.Spatial.DbGeography - 沒有無參數構造函數

<div class="form-group"> 
      @Html.LabelFor(model => model.Location.Longitude, new { @class = "control-label col-md-2" }) 
      <div class="col-sm-3"> 
       @Html.TextBoxFor(model => model.Location.Longitude) 
       <img class="load-icon" src="~/Content/Loading.gif" /> 
       @Html.ValidationMessageFor(model => model.Location.Longitude) 
      </div> 

      @Html.LabelFor(model => model.Location.Latitude, new { @class = "control-label col-md-2" }) 
      <div class="col-sm-3"> 
       @Html.TextBoxFor(model => model.Location.Latitude) 
       <img class="load-icon" src="~/Content/Loading.gif" /> 
       @Html.ValidationMessageFor(model => model.Location.Latitude) 
      </div> 
     </div> 

在我的控制,我收到對方形式:

[HttpPost] 
    [ValidateAntiForgeryToken] 
    public ActionResult Create([Bind(Include = "...Location...")] Report report) 

但是每次我用表單中的值POST時都會拋出一個異常,說明某個對象(它告訴我哪個對象)沒有參數少的構造函數。當我從綁定字符串中刪除「位置」,但保留所有其他屬性(在我的示例中省略),它工作正常。

這似乎表明問題在於它試圖創建一個DbGeography來放入「報告」,但由於無法實例化而失敗。它是否正確?如果是這樣,我該如何避免這個錯誤?我寧願不在數據庫中使用自定義類,但我想不出任何其他選項。

+0

擁有DBGeography默認構造函數? – Zinov

+0

它不是沒有參數的公共構造函數 –

+0

所以,如果這不是公共構造函數,那麼你的期望 - 這是你的答案 –

回答

0

它使用sqlQueryCommand 這個代碼100%的最佳方式工作:

var id = form["id"]; 
      var name = form["name"]; 
      var lat = form["Location.Latitude"]; 
      var lng = form["Location.Longitude"]; 
      db.Database.ExecuteSqlCommand("insert into [dbo].[schoolinfo] values ('" + id + "','" + name + "',geography::Point(" + lat + ", " + lng + ", 4326))"); 
+0

不,這根本不安全,不這樣做。 – JOSEFtw

+0

爲什麼不呢? @JOSEFtw –

+0

我有問題綁定dbGeography,所以我選擇formcollection和sqCommand –