I am a beginner programmer and faced a problem, how to avoid mass assignment, for now i got only two very small Entities Author and Book.
public class Book
{
public Book()
{
Authors = new List<Author>();
}
public int? BookId { get; set; }
public string Title { get; set; }
public IList<Author> Authors { get; set; }
}
And I wanted to avoid assignment (bookInDb.Title = book.Title) when I am updating a book:
public void UpdateBook(Book book)
{
var bookInDb = GetBook(book.BookId.Value);
bookInDb.Title = book.Title; // I want this logic to be replaced in more elegent way
var authorsInDb = bookInDb.Authors.Select(f => f.AuthorId).ToList();
var editedAuthors = book.Authors.Select(f => f.AuthorId).ToList();
var authorToAdd = GetAuthorsToAdd(authorsInDb, editedAuthors);
authorToAdd.ToList().ForEach(x=>bookInDb.Authors.Add(x));
var authorsIdToRemove = authorsInDb.Except(editedAuthors);
var authorsToRemove = AuthorsToRemove(bookInDb.Authors, authorsIdToRemove);
authorsToRemove.ToList().ForEach(x => bookInDb.Authors.Remove(x));
_dbContext.SaveChanges();
}
For now It is not a problem, but if I would have more fields, am I supposed to that in this way or there is much easier way ? Thanks for Your answers.
UpdateBook([Bind(Exclude = "Title")] Book book)
更多信息和更多方法在这里 。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.