HttpPut Route api update usercard books public IHttpActionResult Updat

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
[HttpPut]
[Route("api/update/usercard/books")]
public IHttpActionResult UpdateUserCard([FromBody]JObject requestBody) { //DEBUG
try {
UserCardModel userCard = requestBody["usercard"].ToObject<UserCardModel>();
IEnumerable<BookModel> books = requestBody["books"].ToObject<IEnumerable<BookModel>>();
logger.Info(String.Format(Properties.Resources.UserCardUpdating, userCard.Id));
// doesn't work
registrationService.UpdateUserCard(
mapper.Map<UserCardModel, UserCardDTO>(userCard),
mapper.Map<IEnumerable<BookModel>, IEnumerable<BookDTO>>(books)
);
logger.Info(String.Format(Properties.Resources.UserCardUpdated, userCard.Id));
return Ok();
} catch (UserCardNotFoundException e) {
logger.Error(e.Message);
return InternalServerError(e);
}
}
public void UpdateUserCard(UserCardDTO userCard, IEnumerable<BookDTO> books) { //DEBUG
try {
//returns only that books which exist in database and intersect with "books"
IEnumerable<Book> existingBooks = (
unitOfWork.Books.FindIntersecting(
mapper.Map<IEnumerable<BookDTO>, IEnumerable<Book>>(books),
new GenericEqualityComparer<Book>(x => x.Id)
)
);
UserCard originalUserCard = unitOfWork.UserCards.GetSingle(x => x.Id == userCard.Id);
unitOfWork.UserCards.Update(
originalUserCard,
new GenericEqualityComparer<UserCard>(x => x.Id)
);
foreach (var book in existingBooks)
originalUserCard.Books.Add(book);
unitOfWork.Commit();
} catch (EntityNotFoundException e) {
throw new UserCardNotFoundException(e.Message, e);
}
}
public IEnumerable<TEntity> FindIntersecting(IEnumerable<TEntity> entities, IEqualityComparer<TEntity> comparer) {
//TODO add exception check
return context.Set<TEntity>().AsEnumerable().Intersect(entities, comparer).ToList(); ;
}