避免质量分配MVC

时间:2015-02-12 10:07:33

标签: c# model-view-controller

我是一名初学程序员并面临一个问题,如何避免大规模分配,现在我只有两个非常小的实体作者和书。

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; }
}

我想在更新图书时避免作业(bookInDb.Title = book.Title):

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();
    }

现在这不是一个问题,但如果我有更多的领域,我是否应该以这种方式或者更容易的方式? 谢谢你的回答。

1 个答案:

答案 0 :(得分:1)

UpdateBook([Bind(Exclude = "Title")] Book book)

更多信息和更多方法here