2014-10-28 57 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