【发布时间】:2017-06-02 08:14:45
【问题描述】:
我是 Angular 和 Entity 框架的新手。 这是来自我的 AngularJS 控制器的代码:
$scope.add = function () {
$scope.loading = true;
alert(this.newMovie.Name);
debugger;
$http.post('api/Movie/', this.newMovie).then(function onSuccess(response) {
alert("Added Successfully!!");
debugger;
$scope.showAddMovieForm = false;
$scope.movies.push(response);
$scope.loading = false;
}).catch(function (response) {
$scope.error = "An Error has occured while adding movie! :(" + response.data;
$scope.loading = false;
});
};
这是我在 MVC 中的 MovieController 中的 Action 方法的外观:
public HttpResponseMessage Post(Movie movie)
{
if (ModelState.IsValid)
{
// _db.People.Where(na => movie.Actors.Any(a => a.PersonId == na.PersonId));
_db.Movies.Add(movie);
_db.SaveChanges();
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, movie);
response.Headers.Location = new Uri(Url.Link("DefaultApi", new { movieId = movie.MovieId }));
return response;
}
else
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
}
}
电影模型类:
public partial class Movie
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Movie()
{
this.Actors = new HashSet<Person>();
}
public int MovieId { get; set; }
public string Name { get; set; }
public Nullable<short> YearOfRelease { get; set; }
public string Plot { get; set; }
public byte[] Poster { get; set; }
public Nullable<int> ProducerId { get; set; }
public virtual Person Producer { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Person> Actors { get; set; }
}
当我在 JS 代码中放置一个调试器时,我可以看到 Angular 正在以正确的格式传递对象。
但不知何故,当它到达 Action 时,“Movie”模型采用“Name”属性值“Actors”对象,该对象是“Movie”本身的一部分。
无法理解“电影”模型为何获得“演员”的“名称”属性。
【问题讨论】:
标签: angularjs asp.net-mvc entity-framework asp.net-web-api asp.net-web-api2