MVVM ViewModel and Model Responsibilities (WPF) - mvvm

I am trying to understand the MVVM pattern and I don't clearly get the responsibilities of VM and M. I am trying to work on an wpf example with a Person class (with firstName, lastName and dateOfBirth). I have created such a class in my Model folder. Now I want a collection (an ObservableCollection) of the Person class that I want to bind to my View. Where should I maintain this collection? In ViewModel or Model?

Here is tutorial They created very similar program to yours.
In MODEL you should have class Person and add persons to collection.
In VIEWMODEL ICmmand etc. Read data from Model and push to View.
In View just display data.

Related

converting swift 3 project to use CoreData

I'm relatively new to Swift and Cocoa worlds and would love to get peoples opinions on whats the best way to design the data model for the following:
I currently have a prototype project for macOS that has the following (simplified) data model:
class Loan: NSObject, XMLParseDelegate {
var id: Int
var address: Address
// ... other properties and methods
func parseZillow() {
// bunch of code, etc
}
}
where Address is another class structure that has its own properties and methods. I then have an array of [Loan] bound to NSArrayController and NSTableView using Cocoa Bindings (and everything works nicely, except now i want to introduce persistent storage into the picture)
Now the (two-part) question:
1) if i was to represent this structure with CoreData model - how do I represent the nested class structure of loan.address path? do i just have 2 Entities in CoreData (Loans and Addresses) and have a one-to-one relationship between the two? is this the best practice?
2) my understanding of CoreData is that instead of using the Array of [Loan] as my data model, CoreData will be the new data model (and will create a managed object representing my data schema similar to what i have currently as my class Loan object. Where would I define the methods that I currently have for my Loan and Address classes? Do I need to create a wrapper class on top of the MO? I've looked at a bunch of tutorials but this part is still not clear to me
Yes, you can have two entities, Loan and Address. If each loan has one address and each address has one loan the relationship is one-to-one. If an address can have multiple loans, the relationship is many-to-one.
From Creating and Saving Managed Objects
Creating NSManagedObject Subclasses
By default, Core Data will return NSManagedObject instances to your application. However, it is useful to define subclasses of NSManagedObject for each of the entities in your model. Speciflcally, when you create subclasses of NSManagedObject, you can define the properties that the entity can use for code completion and you can add convenience methods to those subclasses.
To create a subclass of NSManagedObject, in Xcode’s Core Data model editor, select the entity, and in the Entity pane of the Data Model inspector, enter the name in the Class field. Then create the subclass (AAAEmployeeMO) in Xcode.
'Create NSManagedObject Subclass…' is in the Editor menu. You can create all subclasses at once. You can add your methods to the NSManagedObject Subclasses.

MVVM viewmodel and model questions

I'm trying to learn MVVM, and i'm struggling a little on differentiating between a model and viewmodel.
If someone could answer these 2 questions it would help clear a lot up for me:
Say I have an Objects class, which is a viewmodel that contains multiple ObservableCollections of Object.
The Object class contains an ObservableCollection of strings that are displayed on the GUI.
Is the Object class a model or viewmodel?
What if the Object class contains just a string and a integer (name and value), is it a model or viewmodel?
The Model is the class that holds your data. The data can be strings /integers or whatever.
The Model can also be a list / collection of those objects. For example a List of Person objects can still be your Model.
The ViewModel is the tier between your Model and the View. It should be used to perform whatever tasks you need on the data (for instance, if your Model is a list of Person objects but you only want to show in your view people that are aged older then 18, this logic is done in the ViewModel)
So to answer your question:
If you have an object which contains the data (in your example a list of strings) it is the Model.
Even if the object is a little more complex (with relation to the number of properties it holds) it's probably still the Model.
Business Logic should be kept separate from the model. On the other hand Validation can be added to the Model (for instance to make sure the Age property of a person is non-negative) since this is still rules on how your data should behave

what is difference between a Model and an Entity

I am confused to understand what is the meaning of this words:
Entity, Model, DataModel, ViewModel
Can any body help me to understanding them please? Thank you all.
The definition of these terms is quite ambiguous. You will find different definitions at different places.
Entity: An entity represents a single instance of your domain object saved into the database as a record. It has some attributes that we represent as columns in our tables.
Model: A model typically represents a real world object that is related to the problem or domain space. In programming, we create classes to represent objects. These classes, known as models, have some properties and methods (defining objects behavior).
ViewModel: The term ViewModel originates from the MVVM (Model View ViewModel) design pattern. There are instances in which the data to be rendered by the view comes from two different objects. In such scenarios, we create a model class which consists of all properties required by the view. It’s not a domain model but a ViewModel because, a specific view uses it. Also, it doesn’t represent a real world object.
DataModel: In order to solve a problem, objects interact with each other. Some objects share a relationship among them and consequently, form a data model that represents the objects and the relationship between them.
In an application managing customer orders, for instance, if we have a customer and order object then these objects share a many to many relationship between them. The data model is eventually dependent on the way our objects interact with each other. In a database, we see the data model as a network of tables referring to some other tables.
To know more about object relationships visit my blog post: Basics of Object Relationships
For more details visit my blog post: Entity vs Model vs ViewModel vs DataModel
I hope I've not missed your point here king.net...
Anyway, presuming you're talking about entity modelling or entity-relationship modelling (ERDs):
an entity represents any real world entity - e.g. student, course,
an entity will have attributes - e.g. student has first name, surname, date-of-birth
an entity will have relationships - e.g. student "is enrolled on" course (where student and course are entities with attributes and "is enrolled on" is the relationship.
the relationship may be "one-to-one", "one-to-many" or "many-to-many" - e.g. one student "is enrolled on" many courses and similarly one course "has" many students.
relationships also have cardinality
Adding relationships between entities creates a "data model". You've modeled some real world system and the internal entities/ objects in that system. Next step is to normalise it to ensure it meets "normal form".
In ERD terms, you may have "logical" and "physical" models. The logical describes the data-model in simple high-level terms that witholds the technical detail required to implement it. It represents the system solution overview. The physical model includes technical details required to actually implement the system (such as "many-to-many join tables" needed to implement "many-to-many" relationships).
Here are some tutorials on-line (though I'm sure there must be thousands):
http://www.maakal.com/maakalDB/Database101ERDpart1.htm
http://www.itteam-direct.com/gwentrel.htm
http://www.bkent.net/Doc/simple5.htm
I'm not quite sure what you mean by "model" and "view model" in a related context. Not sure if you may be confusing this with Model-View-Controller paradigm (MVC). Here, a model is some data component and the view represents an observer of that data (such as a table or graph UI component). There's lots on-line explaining "model view controller" or "MVC".
Hope this helps, Wayne
Entity:
An entity is the representation of a real-world element within Object Relational Mapping (ORM) as the Entity Framework. This representation will be mapped to a table in a database and its attributes will be transformed into columns. An entity is written using a POCO class that is a simple class, as you can see in the following example in C#:
using System;
using System.Collections.Generic;
using System.Text;
namespace MyAplication.Entity
{
public class Person
{
public long PersonId { get; set; }
public string Name { get; set; }
public short Age { get; set; }
}
}
Working with UI creation is a complex task. To keep things organized, programmers separate their applications into layers.
Each layer is responsible for a task and this prevents the code from being messed up. It is in this scenario that the architectural patterns like the MVC and the MVVM appear.
Model:
Within the MVC we have a layer responsible for representing the data previously stored, a given could be an instance of a person modeled in the previous example. This layer is the Model. This template will be used to construct the view.
ViewModel:
A ViewModel in the MVVM architecture is much like a Model in the MVC architecture. However a ViewModel is a simplified representation of the data with only the information that is required for the construction of a view.
using System;
using System.Collections.Generic;
using System.Text;
using MyAplication.Web.ViewModel.BaseViewModel;
namespace MyAplication.Web.ViewModel.Person
{
public class PersonNameViewModel : BaseViewModel<string>
{
//I just neet the name
public string Name { get; set; }
}
}
DataModel:
It is simply an abstract model (this model is different from the MVC layer model) which establishes the relationships that exist between the elements that represent real-world entities. It is a very comprehensive subject.
First of all,to know about Entity you must know about Class.
All of them represent same fields but the terminology changes based on declaration.
Let us consider a table from any database[SQL,ORACLE,Informix,Cassandra..] as example.
CLASS:
Generally a table is a considered as a class until it is added to edmx or dbmx.
//Student class
public class Student()
{
//Properties
public int StudentNumber;
public string StudentName;
}
ENTITY:
After drag drop/adding the table into dbmx/edmx it is referred to as
Entity.
Each Entity is generated from its corresponding class and we can add
attributes to entity which are used for performing operations using
linq or entity.
DATAMODEL:
Contains all the fields in table.
DATAMODEL is a direct class reference to your cshtml or controller
where you can access the attributes to perform CRUD operations.
VIEWMODEL:
Some situations occur where we need to perform CRUD operations more
than one model(table).
So we combine all our required models in a class and define them in
its constructor.
Example:
Lets assume
//Student class
public class Student()
{
//Properties
public int StudentNumber;
public string StudentName;
}
//Marks Class
Public class Marks()
{
public int Maths;
public int Physics;
public int Chemistry;
//Now sometimes situations occur where we have to use one datamodel inside //other datamodel.
public Student StudentModel;
}
Simple talk:
DTO stands for Data Transfer Object. DTOs are mainly used for transferring data between services (web services, APIs, etc.) which can encompass variety of properties of different entities (with or without their ID). Take this row as an example of a DTO: Consider that a shopping website is going to send its shipping requests to a shipping company by a web-service. Its DTO would be something like this: CustomerFullName, ShippingFee, ShippingAddress. In this example CustomerFullName is combination of properties FirstName + LastName for the Customer entity, and ShippingFee is the result of several processes of destination, tax, etc over some other entities.
On the contrary, Entities are bunch of properties gathered to represent a single entity with a specific ID (e.g., Teacher, Student, Employee, etc.). In other words, DTOs are a bunch of meaningless properties gathered to be sent to the client and a DTO doesn't necessarily have relationship to the other DTOs, while an Entity includes properties of a specific object with meaningful relation to the other entities. In a relational database paradigm, we can look at DTOs as views' row while Entities are tables' row with the primary key.
However, Model is a combination of these two. A model can contain several related entities plus extra data to handle real-world application/UI problems. Consider a Model named CustomerOrdersModel that contains Customer Entity, List<Order> Entities, and an extra Boolean flag PayWithCredit specifying whether user is going to pay with debit-card or credit-card.

Is this a view model?

I'm still new to MVVM and am trying to understand the concepts.
I have a class generated by Linq To Sql for a table.
I want this class to look different, so I create a new class with some of the properties from the generated class and a few new properties, that is only dependent on generated class.
Is this class a model, a view model or something different?
ViewModel represents the state and behavior of the View. I would call a class a ViewModel if:
It provides property change notification through INotifyPropertyChanged
Has commands for the view
Provies a model for the view, by specializing the model for easier data binding (formatting etc)
Could be a View Model, but not necessarily. Are these extra properties there for the purpose of supporting a view. If yes, then you could argue that it's a view model class.
View Models exist because views exist. Models exist because you have a domain of data. the View Model greases the skids between reality (model) and a given users perception of that reality (the view)

MVC 2 Application with a relational DB and object wrappers - how to get relational data into views?

I've recently refactored my application with the following:
Linq to SQL db connection
Objects to wrap the linq to sql classes
Mappers to map back and forth between objects and Linq to Sql entitys
Service layer to call the repository, handing up objects to the UI.
Before I was just using Linq to SQL objects in my UI (I know). But when displaying relations it was so easy. For instance:
I have a able called SchoolProfile, and a table called School. A user has a SchoolProfile (with GPA, Rank, etc..) , which links to a School. The School adding functionality was easy - because it has no foreign keys.
When creating a form for a user to list all SchoolProfiles - they dont want to see a SchoolId. Before in my view it would simply be schoolprofile.School.Name. Now a ShoolProfile is a "flat" object in my ViewData with no properties. I guess I could create other classes to get the related data (name of the school, etc..) but that feels messy. Any suggestions?
My suggestion is to look at ViewModels and AutoMapper. Basically you will create a specific ViewModel for your View and you can include SchoolName as a property of that ViewModel. Then you can use AutoMapper to map from your Domain Model (form Linq to Sql) to your ViewModel easily.
Basically, you want your View to get all the information it needs from the ViewModel. So design your ViewModel based on all the info you need to display. So all it needs to do is take what is in the ViewModel and spit it out.