C# “后错误”;转换值时出错';ID';输入“;到
我改变了我的工作和CustomerEmployee类之间的关系,我试图发表一篇文章,但我得到了一个错误。使用断点,我看到Id没有返回到apiController。我做了一些搜索,我认为这可能是一个Json问题,不知道如何纠正它。我有6个Id,我正试图张贴,但他们的设置相同,所以我会显示其中一个代码 错误消息C# “后错误”;转换值时出错';ID';输入“;到,c#,angularjs,asp.net-web-api2,asp.net-mvc-5.1,C#,Angularjs,Asp.net Web Api2,Asp.net Mvc 5.1,我改变了我的工作和CustomerEmployee类之间的关系,我试图发表一篇文章,但我得到了一个错误。使用断点,我看到Id没有返回到apiController。我做了一些搜索,我认为这可能是一个Json问题,不知道如何纠正它。我有6个Id,我正试图张贴,但他们的设置相同,所以我会显示其中一个代码 错误消息 $id: "1" Message: "The request is invalid." ModelState: {$id:2, newJob.CustomerEmployeePMId:[,…
$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: [,…]
看法
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 }
);
高级控制器
//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');
});
});
};
// 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 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没有从角度控制器中出来
“将值10转换为类型“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; }
}
根据我所看到的,我认为弗洛里安是对的。您的代码可能如下所示:
public class Job
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public Int64 JobId { get; set; }
public int CustomerEmployeeAccountantId { get; set; }
public virtual CustomerEmployee CustomerEmployeeAccountant { get; set;}
}
对象应该同时引用键(CustomerEmployeeAccountAnti)和对象(CustomerEmployeeAccount)。代码失败的原因是DB链接位于Id之间,因此尝试将10分配给属性。“Id”属性应该是int
通过添加额外的虚拟属性,您告诉Entity Framework“嘿,把外键的Id放在Id属性中,然后根据外键关系用关联数据填写CustomerEmployee对象。”
然后,如果您想访问CustomerEmployeeAccounter数据,那么它应该在API返回的JSON对象中的标记为CustomerEmployeeAccounter的属性中可用
小心点。我注意到WebApi和EF在处理递归对象时并不总是很好,所以我个人会在将这些数据传递给客户端之前将其转储到ViewModel中。有很多方法可以关闭它/改变它的行为,但我非常喜欢只返回您需要的内容来最小化带宽
此外,这只是个人偏好,但似乎是大多数微软文档的发展方向,是支持long而不是int64。这是相同的数据类型,但我注意到了使用long实现命名一致性的趋势。不过,Int64在技术上是正确的
更新:
查看您的屏幕截图,尝试从var data={}更改变量名;到var postData={};。我看不到代码的其余部分,但看起来有几个名为data的变量。这可能会导致冲突吗?您的模型
CustomerEmployeeAccountAnti
上的属性类型为CustomerEmployee
,即它是一个对象,而不是ad id。您在Json中将它设置为10,因此,模型绑定器表示它无法将值10
绑定到类型为CustomerEmployee
的属性。您需要将可以反序列化的json发送到CustomerEmployee
,或者将模型上的属性更改为int。我如何反序列化它,我无法将其更改为int,因为我将失去我的关系。只要发布的json有效,它将自动反序列化。这就是模型绑定器的神奇之处。在这种情况下,我如何发布有效的JSON问题是我如何与CustomerEmployee类建立关系。如果我将其更改为“int”,它与它没有连接,我会在一秒钟内尝试。添加迁移时出错。序列包含多个元素
public class Job
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public Int64 JobId { get; set; }
public int CustomerEmployeeAccountantId { get; set; }
}
public class Job
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public Int64 JobId { get; set; }
public int CustomerEmployeeAccountantId { get; set; }
public virtual CustomerEmployee CustomerEmployeeAccountant { get; set;}
}