2014-10-28 37 views
0

我改變了我的工作和CustomerEmployee類之間的關係,我試圖做一個帖子,我得到一個錯誤。使用一個斷點,我發現這個Id沒有返回到apiController。我做了一些搜索,我認爲它似乎可能是一個JSON問題,不知道如何糾正它。我有6級編號的我想發表,但它們是建立相同的,所以我會告訴代碼其中之一發佈錯誤,「錯誤轉換值ID」鍵入「到

錯誤消息

$id: "1" 
Message: "The request is invalid." 
ModelState: {$id:2, newJob.CustomerEmployeePMId:[,…], newJob.CustomerEmployeeAdminId:[,…],…} 
$id: "2" 
newJob.CustomerEmployeeAccountantId: [,…] 
0: "Error converting value 10 to type 'TexasExteriorSPA.Models.CustomerEmployee'. Path 'CustomerEmployeeAccountantId', line 1, position 150." 
newJob.CustomerEmployeeAdminId: [,…] 
newJob.CustomerEmployeePMId: [,…] 
newJob.CustomerEmployeeSuperintendentId: [,…] 

視圖

<select class="form-control" ng-options="customer.CustomerEmployeeId as customer.CustomerEmployeeFirstName + ' ' + customer.CustomerEmployeeLastName for customer in customerEmployeeArray | filter:{CustomerEmployeeRole : 'Accountant', CustomerId : currentItem.CustomerId} " ng-model="currentItem.CustomerEmployeeAccountantId"> 
    <option value="" selected="selected">Customer Acct</option> 
</select> 

角控制器

//Post New Job 
$scope.submitJob = function() { 
    var data = { 
     JobId: $scope.JobId, 
     CustomerEmployeeAdminId: $scope.currentItem.CustomerEmployeeAdminId 
    } 
    $http.post('/api/apiJob/PostNewJob', data).success(function (data, status, headers) { 
     console.log(data); 
       $scope.openNewJobModal.then(function (m) { 
        m.modal('hide'); 
       }); 
    }); 
}; 

WebApiConfig

// Web API configuration and services 
     var json = config.Formatters.JsonFormatter; 
     json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects; 
     config.Formatters.Remove(config.Formatters.XmlFormatter); 
     // Web API routes 
     config.MapHttpAttributeRoutes(); 

     config.Routes.MapHttpRoute(
      name: "DefaultApi", 
      routeTemplate: "api/{controller}/{id}", 
      defaults: new { id = RouteParameter.Optional } 
     ); 
     config.Routes.MapHttpRoute(
      name: "JobApi", 
      routeTemplate: "api/{controller}/{id}", 
      defaults: new { controller = "apiJob", id = RouteParameter.Optional } 
     ); 

apiController

// POST api/<controller> 
    public async Task<IHttpActionResult> PostnewJob([FromBody]JobViewModel newJob) 
    { 
     if (!ModelState.IsValid) 
     { 
      return BadRequest(ModelState); 
     } 

     using (var context = new ApplicationDbContext()) 
     { 
      var job = new Job(); 

      Mapper.CreateMap<JobViewModel, Job>(); 
      Mapper.Map(newJob, job); 

      context.Jobs.Add(job); 

      await context.SaveChangesAsync(); 

      return CreatedAtRoute("JobApi", new { job.JobId }, job); 
     } 
    } 

作業類

public class Job 
{ 
    [Key] 
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)] 
    public Int64 JobId { get; set; } 
    public CustomerEmployee CustomerEmployeeAccountantId { get; set; } 
} 

CustomerEmployee類

public class CustomerEmployee 
{ 
    [Key] 
    public int CustomerEmployeeId { get; set; } 
    public string CustomerEmployeeFirstName { get; set; } 
    public string CustomerEmployeeLastName { get; set; } 
    public string CustomerEmployeeRole { get; set; } 

    public Int64? CustomerId { get; set; } 
    public virtual Customer Customer { get; set; } 

} 

更新,它看起來像ID是不可以這樣做出來的角控制器的 pic pic2

+0

您的模型'CustomerEmployeeAccountantId'上的屬性的類型爲'CustomerEmployee',即它是一個對象而非ad id。看起來你在Json中將它設置爲10,所以模型綁定器說它不能將值'10'綁定到'CustomerEmployee'類型的屬性。您可能需要將可以反序列化的json發送到'CustomerEmployee',或者將模型中的屬性更改爲int。 – 2014-10-28 14:42:58

+0

我將如何反序列化它,我無法將其更改爲int,因爲我將失去我的關係 – texas697 2014-10-28 17:19:54

+0

只要發佈的JSON有效,它就會自動進行反序列化。這是模型活頁夾的魔力。 – 2014-10-28 17:28:46

回答

1

基於我所看到的,我認爲弗洛裏安是對的。您的代碼也許應該是這樣的:

public class Job 
{ 
    [Key] 
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)] 
    public Int64 JobId { get; set; } 

    public int CustomerEmployeeAccountantId { get; set; } 
    public virtual CustomerEmployee CustomerEmployeeAccountant { get; set;} 
} 

你的對象應該有兩個密鑰(CustomerEmployeeAccountantId)和對象(CustomerEmployeeAccountant)的參考。您的代碼失敗的原因是您的數據庫鏈接位於Id的之間,因此試圖將其分配給該屬性。 「Id」屬性應該是一個int。

通過添加額外的虛擬屬性,您告訴實體框架「嘿,將外鍵的Id放在Id屬性中,然後繼續並使用基於外鍵關係的關聯數據填充CustomerEmployee對象「。

然後,如果您想要訪問CustomerEmployeeAccountant數據,它應該在您的API在標記爲CustomerEmployeeAccountant的屬性中返回的JSON對象中可用。

只要小心。我注意到WebApi和EF並不總是能夠很好地處理遞歸對象,因此在將它傳遞給客戶端之前,我會親自將這些數據轉儲到ViewModel中。有許多方法可以關閉/改變行爲,但我非常喜歡僅僅爲了最小化帶寬而返回的東西。另外,只是個人偏好,但它似乎是微軟文檔大部分文檔發展的方向,而不是長於int64。這是相同的數據類型,但我已經注意到長時間使用命名一致性的趨勢。 Int64在技術上是正確的。

UPDATE:

看你的截圖,從VAR數據試圖改變你的變量名= {};以var postData = {} ;.我看不到剩下的代碼,但看起來有幾個名爲data的變量。這是否會導致衝突?

+0

將在一秒內嘗試。添加遷移時出現錯誤。序列包含多個元素 – texas697 2014-10-29 05:30:50

1

"Error converting value 10 to type 'TexasExteriorSPA.Models.CustomerEmployee'是相關行。看起來好像你正在將10的值作爲CustomerEmployeeAdminId。 C#現在嘗試將給定的對象轉換爲JobViewModel類型的對象,並在它想將10轉換爲CustomerEmployee時失敗。你可以這樣做來解決它:

public class Job 
{ 
    [Key] 
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)] 
    public Int64 JobId { get; set; } 
    public int CustomerEmployeeAccountantId { get; set; } 
} 
+0

問題在於我是如何與CustomerEmployee類建立關係的。如果我將它更改爲'int',它與它沒有任何聯繫 – texas697 2014-10-28 17:19:22