我更改了我的Job和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; }
}
客户员工类别
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不在Angular Controller中
Based on what I can see, I think that Florian has it right. Your code should probably be something like:
public class Job
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public Int64 JobId { get; set; }
public int CustomerEmployeeAccountantId { get; set; }
public virtual CustomerEmployee CustomerEmployeeAccountant { get; set;}
}
Your object should have a reference to both the Key (CustomerEmployeeAccountantId) and the object (CustomerEmployeeAccountant). The reason your code is failing is that your DB link is between the Id's, hence the 10 that's trying to be assigned to the property. The "Id" property should be an int.
By adding the additional virtual property, you're telling Entity Framework "Hey, put the Id of the Foreign Key in the Id property and then go ahead and fill out CustomerEmployee object with the associated data based on the Foreign Key relationship."
Then, if you want to access the CustomerEmployeeAccountant data, it should be available in the JSON object returned by your API in a property marked CustomerEmployeeAccountant.
Just be careful. I've noticed that WebApi and EF don't always do so well with recursive objects, so I'd personally dump this data into a ViewModel before it's passed to the client. There are ways to turn it off/change the behaviour, but I'm huge fan of only returning exactly what you need to minimize bandwidth.
Also, just a personal preference, but it seems to be the direction that most of Microsoft's documentation is headed, is to favor long over int64. It's the same data type, but I've noticed the trend of using long for naming consistency. Int64 is technically correct though.
UPDATE:
查看屏幕快照,尝试从var data = {}更改变量名。到var postData = {};。我看不到其余的代码,但看起来有几个名为data的变量。那会引起冲突吗?
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句