Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where does business logic sit in MVVM?

I am used to developing with N-Tier architecture, i.e. Data Access Layer, Business Logic Layer, etc

Can anyone provide any advice or links about the best location for my business logic?

Do I put all of this into classes within the Models folder of my Silverlight application?

Paul

like image 638
Paul Avatar asked Jun 09 '12 19:06

Paul


2 Answers

I faced the same problem and decided to go this way: I created classes like controllers in MVC (performing some actions with my model) and I work with them in all ViewModels.

For example: our application has a list of books. We need to add/edit/delete them.

So we have a model:

public class Book 
{
    public int BookId { get; set; }
    public string Title { get; set; }
    public string Author { get; set; }
}

Then we have a controller class:

public class BookController 
{
    string dbPath = ...;

    public void AddBook(string title, string author)
    {
        var book = new Book() { Title = title, Author = author };
        AddBook(book);
    }

    public void DeleteBook(int id)
    {
        using (var db = new SQLiteConnection(dbPath))
        {
            db.Delete<Book>(id);
        }
    }

    public void DeleteBook(Book book)
    {
        using (var db = new SQLiteConnection(dbPath))
        {
            DeleteBook(book.BookId);
        }
    }

    public List<Book> GetAllBooks()
    {
        using (var db = new SQLiteConnection(dbPath))
        {
            return db.Table<Book>().ToList();
        }
    }

    public Book FindBook(string title, string author, int id)
    {
        .....
    }
}

Now we can use it wherever we need, e.g.:

public class BookListViewModel : ViewModelBase 
{
    public BookListViewModel() 
    {
        GetData();    
    }

    private void GetData()
    {
        BookController bc = new BookController(); // here we start using our controller. 
        _books = new List<Book>();
        _books = bc.GetAllBooks();
     }
}

Such approach helps us:

  1. keep all business logic separately (in controller class)
  2. avoid code duplication
like image 170
QArea Avatar answered Oct 13 '22 15:10

QArea


Business logic, as well as the data, is typically part of the Model layer in MVVM. The View is the visuals, and the ViewModel is the "glue" that lets you work with the business specific logic and data.

Anything that's specific to the domain or business should be reusable by other applications, using other architectures.

like image 29
Reed Copsey Avatar answered Oct 13 '22 16:10

Reed Copsey