Thursday, October 15, 2015

Why would you change the way you write your code?

When I first time adopted the way I write my code it was the way I learned so it was natural for me to write it that way. I sometimes came across the code that uses, for example query string inside C# like "SELECT SomeRow FROM SomeTable WHERE Something = Something" and that had perfect sense for me. But other times I came to something like "@ammount" and seeing it written in the same SqlCommand method/class, I tought to my self "Why are they using this when you can achieve the SAME thing with the way, I write it?" I wanted to know "Why?". What is the difference of using this from the other way and what is the reason to it?

Whenever I had a need to write an SQL query like "INSERT INTO someTable VALUES()" inside of C# I had to always take a really good care of what amount of "''' I do and how many spaces I have, debug with pointer to check how is my string being written and why I keep getting that error when I know that my query inside SQL Menagement Studio works. This is one of the reasons your code can be written differently. Main goal that we want to acheive here is to have a good readability.

Lets say you have inside your C# code written this:

string myQuery = "INSERT INTO myTable VALUES('"+ someVar +"','"+ someVar1+"', "'+someVar2+"')"

As you can see you can easily loose the track of how many "''" you wrote. Sure on this example it is not that hard, but imagine you have a query that checks if something exists (IF EXISTS) then you have UPDATE of some data then if that something does not exists and you then have to do a whole another set of values and you have 6 variables to fill...it gets really...really...easy to loose it. I mean really.

I know I was thinking when I used this way of typing like "well it works?! why does it metter?" but when you do this too offten you want something to read it more "easier". Better said, lighter way to read it.

One of the way we can do that is by writting the same query in a bit different way.


 string myQuery = string.Format("INSERT INTO myTable VALUES('{0}','{1}','{2}')",
                                            someVar, 
                                            someVar1,
                                            someVar2);

How does this look? Does your brain realease liquid of joy trough your eyes? I know mine did! Yet there is more. Sure this is a really good read of your code comparing to previous example. But what if you would have this query repeated everytime you need to check an IF ELSE statement? It would become a bit over-burdening that you would have to change, either, query or position of variables for each of those queries inside IF ELSE statments. I had 26 of them but I bet you can get higher then that. But then we get to a problem of a good maintaince of our code.

So how do we make our code more easier to maintain? In this case since we are using SQL queries, we will use that @funkyThing you probably saw but don't know what is it for. These things are called stored procedures. You should read how do you create one and check it out on your own, but for now you should know that your stored procedure can recieve some types of parameters. And you create these inside your SQL Management Studio database server.

Let's say you have stored procedure simple as this one:

GO
CREATE PROCEDURE mySQLProcedure
    @someVar int, 
    @someVar1 int,
    @someVar2 int
AS 

    SET NOCOUNT ON;
    INSERT INTO myTable VALUES(@someVar, @someVar1, @someVar2)

GO

As you can already probably see, you can always give to this stored procedure different parameters withouth changing your query at every possible place. So now back inside of your C# code you would write something like this:

var cmd = new Command("mySqlProcedure", CommandType.StoredProcedure);
                cmd.CommandParameters.Add(new CommandParameter("@someVar"));
                cmd.CommandParameters.Add(new CommandParameter("@someVar1"));
                cmd.CommandParameters.Add(new CommandParameter("@someVar2"));

if ( mySomethingString.Equals("ble"))
{
                 cmd.CommandParameters[1].Value =  1;
                 cmd.CommandParameters[2].Value = 2;
                 cmd.CommandParameters[3].Value = 3;
}

if ( mySomethingString.Equals("bleble))
{
                 cmd.CommandParameters[1].Value = 3;
                 cmd.CommandParameters[2].Value = 4;
                 cmd.CommandParameters[3].Value = 5;
}
. . .

This might look like "what the hell is this ?!?!" but when you think about it and actually see what is going on, you would see that now if you would at any point need to change values its much less time consuming, and more readable then you would otherwise need.

There is always a way you can optimize your code to gain this two things. Readability and Maintance. But if you still wonder "okey but why?!" as I did, good readability and maintance leads to a less error prone code. The less errors your application have the better it will work. Ofcourse, for your applications to be even less with errors there is something called Test Driven Development. And your readability and maitance will just help you with it.

I will not cover Test Driven Development here because there is a bit longer story and in most cases it will involve removing some dependancies in your code but for now, I hope this post helps you in seeing that what you change with your code is not always unnecessary as you would originaly think, but instead help you maintain the code of your applications with more ease.

Have fun and stay stronk!



Wednesday, May 27, 2015

Building a Blog - Controller and First Preview of the Blog

We have created Model and Data Access Layer classes in previous posts. Now it is time to create a Controller and see the first View of our Blog.

If you are in this post for the first time I suggest you go to the very first post of this small project for Building a Blog and see what is this all about. You can check it HERE.

Assuming you have the Models and Data Access Layer classes created, you should go to your Controllers folder and add a new Controller. We want to read the data from the database that will be created upon the start of our application and then present that data on the web browser trough the View that we will make. So...

1. Add a new Controller by right-clicking the Controllers folder and then Add, then Controller.

2. On the Add a Scaffold window, choose MVC 5 - Empty

3. Give it a name "PostsController".

You should have your Controllers folder now having one controller like this:

ASP.NET Controller


And your class should look like this:

Empty Controller Class
As you can notice this class we created inherits Controller class, to have the functionalities of the Controller.

What we need to do now is, as we did with the Model creation process, specify to use few class packages. So below using System.Web.Mvc;  we have to again say to this class use Entity Framework package. We add:

- using System.Data;
- using System.Data.Entity;

Then we also need to tell this class that it will use our Models folder or the namespace which our Models are under so that we can access to them as our Context class is under the Models namespace even though it is in a different folder because we changed the namespace in that folder for the Context class:

-  using BlogProject_Dusan_MVC.Models;

Now what we need to set first for this class is to have one instance of our Database Context Class. So right inside  of the class (public class PostController: Controller) you add one private property so that is only accessible to this class like this:

- private BlogContext db = new BlogContext();

Now we need to create a method for our Controller class that will get the data from our database. We make a method like this:

public ActionResult Index()
{

}

ActionResult is the class from an MVC package of classes and we call it Index because it is the most common way to call the first page method for the classes. However, this method will show warning on the Index() because you are not returning any value when using the ActionResult class.

So the next thing we have to write is to read the posts for the blog from the database using Linq and Entity. Inside the Index() method we write:

- var posts = db.Posts.Includep => p.Blog);
return View(posts.ToList());

What we basically did is we set one variable that reads our BlogContext class, and from it Posts table that are connected to the Blog table.

Then we return the value of that variable in a List to the View, that we have to create in order to see what is being listed out. But first, the class you have just created it should look like this:

Controller Class with ActionResult method


If this is how your class look like that is good. But let's make one change in our App_Start folder, then RouteConfig class.

Change the controller="Home" to controller="Posts". What this class is doing is simply set to read our Controller upon the start of the application.

Now do one build of your application. You can do this by either pressing Ctrl+Shift+B or go to Build then choose Build solution.

If no error is shown in the Output Window of Visual Studio it means your code is written out properly. If you do have, you should re-check what you have written and fix the errors that are shown.

Then start an application by either pressing Ctrl+F5 or go to Debug Start Without Debugging. Your application should start and you should get something like this:

ASP.NET MVC View Missing Error

This means that your View cannot be found. Because in the method you have made, you said to return the data to the View but there is no View made that it should use. So go back to your PostsController and right click on the Index() of the method and choose Add View.

View name should be Index, to match the name of the method in the Controller and Template should be Empty.

Once you do that, you will get in the Views folder of your Visual Studio application another folder that is called as your controller is. And inside of that folder a View called Index.cshtml.

If you start your application again, you should see an empty blank web page with the name of your View. Like this:

ASP.NET MVC Empty View Page

So now we should write in our View some code to read the data from our database properly. So go to the view you have Added and open it up.

There should be ViewBag.Title = "Index" you can change this to "Posts" as that is changing the <title></title> tag in the Shared layout page.

And then you have <h2>Index</h2> and you can change this to Posts too, as that is what is being written out on the page. The @{} you see, it is the Razor technology to read some of the C# functions on the page.

But what you need to do is to specify on the very top of the Index.cshtml file, the very first, number 1 line, you need to write this:

@model IEnumerable<BlogProject_Dusan_MVC.Models.Post>

This is saying that this page is using strongly-typed View for the model that is being stored as List, because you said in the method of Controller you are returning a List, and we write IEnumberable as there is a collection of object we need to read.

After the <h2></h2> tag we have to use foreach with Razor to read trough all the elements from the database table EntityFramwork created for us. Like on the next picture:

Index.cshtml page to read data from database.


What is this doing is, for each item in the Model, which in our case it is Post model, display the Title and the Content of our Posts. The <table> is there just to show the items from database in proper order and to look more "user friendly".

So now if you start your application, you should get something like this:

Blog posts read from Database

I know it is just dull 1 2 3 4 numbers and same text, but this is how the posts usually look at the Blogs. You have the title and the content of the post. What next we should do is to create a View where we can Create new posts. But for now...

That is it! However, it is WAY FAR from being perfect or to even call it a proper blog. My goal was to show that you can start with something simple and small and build on that, but also introduce you to some ASP.NET MVC stuff. Now we have a page that reads the Posts and presents them to the user.

There is like tons of other things we can do and well... We must do if we want to have a proper blog. Like first thing that comes to my mind now is, to alter our database tables to have DateTime fields so that we track when the post is being created. Then our Posts need to have a shorter description to give the user some info about what he can read in the post. But then there arises a problem of having the views for the description and the View of that post.

What else... Yeah, we have to have a logging system as well, because what if you want to have couple of Authors for one Blog? Then you have to store somewhere users who are Authors, which means creating another Database table and connecting it with the Blog table so that they match and who has the rights for which Blog to write upon.

Then commenting system as well. Where we need to have a table for Comments. It is like a lot you can do. One of the things is also using Bootstrap to get nice and responsive design. Then I can already see we would have to use Authorizations for the users and...you would say "OMG!! Who is going to do that!?No way! I am off" But...you shouldn't think of it as a lot things to do and I can't do it, but rather think of the challenges you put yourself into and the more you get over each challenge you get that much better. You understand more how things work and you become a great developer.

As for me, I will have to continue working on some applications I need to improve and see how far I can go. If i get time to continue on this Blog creation I will do so and continue writing, if not I will write of the applications I am currently working on.

I sincerely hope that this small series of MVC ASP.NET will be of use to beginners in MVC or anyone who is new to programming as I had need to write something more simple than what I usually do, because I wished sometimes someone had done it for me. If this helps you out, I will be happy.

Till next time, stay tall and keep your head high!

Sunday, May 24, 2015

Building a Blog - Pt3.Database Creation, Context and Intializator Classes

In a previous post, I wrote how to set two Models we will use for a start of the Blog project we are building. In case you have missed it you can read it here, but I strongly suggest that you read the very first post of this Small and Simple Blog and see what is this all about.

We need to tell to Entity Framework what database to create and which tables to have. Therefore, we need to create another class that is being called BlogContext. However, it is good to make this class in a separate folder so that we know where are our classes for making Databases are. I created new folder called DataAccessLayer or just shortly DAL. Inside of it create two new classes, one is called BlogContext other one is called BlogInitializer:

Data Access Layer with Context and Intializer Class
Let's first clear out what is one class doing from the other.

The BlogContext, is inheriting another class that is called DbContext class. This is the part of Object Oriented Programing where each class that inherits another class is maintaining the same behavior of that inherited class. The DbContext class is the class that you get when you install Entity Framework for your project, however, to be able to use this class you must specify the use of the Entity Framework in your class. The BlogInitializer class is just there to fill our Database with something on creation. So go to your BlogContext class and add these lines of code:

========================================================

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;

namespace BlogProject_Dusan_MVC.Models
{
    public class BlogContext :DbContext
    {
        public BlogContext():base("BlogContext")
        { }

        public DbSet<Post> Posts { get; set; }
        public DbSet<Blog> Blogs { get; set; }


        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
           
        }
    }
}

===========================================================

1. As you can notice we have to specify to use the package for Entity Framework by adding using System.Data.Entity; and also Conventions that are being used to create relations between tables in our database. This is mostly for the method called OnModelCreating that you can see.

2. Also, we have to change our namespace from BlogProject_Dusan_MVC.DataAccessLayer_DAL_ to BlogProject_Dusan_MVC.Models so that we include the classes from the Model we have previously created. However, you can do this by adding another using statement line in the top of your code.

3. Then we have to inherit the DbContext class by adding next to BlogContext name the :DbContext, that is how you inherit a class.


4. Then we have a constructor of the class that inherits the constructor fo the DbContext class, but the text written inside the base constructor is actually the name of the string that we will add in the Web.Config file of our project.

5. We then have two DbSet properties that are saying to Entity Framework to create a database table with given models that we have done in previous posts.

6. Finally, we have a method or function of our BlogContext class, that is, using conventions, to remove pluralization of our models. If we didn't do this method our tables in the database would be named Posts Blogs. Instead the table names will be Post, Blog. Think of this line of code as something that is personal preference. Some developers think it should be in pluralization and some think it should be not. So you can include or exclude this OnModelCreating method/function.


BlogInitializer class as previously said, it is there to fill our database with some data. The class looks like this:

=============================================================

using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;

namespace BlogProject_Dusan_MVC.Models
{
    public class BlogInitializer:System.Data.Entity.DropCreateDatabaseIfModelChanges<BlogContext>
    {
        protected override void Seed(BlogContext context)
        {
         
            var blogs = new List<Blog>
            {

                new Blog{Name="Dushan Blog",BlogID=1}
            };
            blogs.ForEach(s => context.Blogs.Add(s));
            context.SaveChanges();


            var posts = new List<Post>
            {
                new Post{Title="This is a Test Title of the Post 1",Content="This is some text 1", BlogID=1},
                new Post{Title="This is a Test Title of the Post 2",Content="This is some text 2", BlogID=1},
                new Post{Title="This is a Test Title of the Post 3",Content="This is some text 3", BlogID=1},
                new Post{Title="This is a Test Title of the Post 4",Content="This is some text 4", BlogID=1}
            };
            posts.ForEach(s => context.Posts.Add(s));
            context.SaveChanges();


        }
    }
}

======================================================================

1. Again, we see that using System.Data.Entity is being specified for this class so that we get EF classes.

2. Then we see that the class BlogInitilaizer inherits the class from Entity Framework and that class is a Generic class that takes our BlogContext as a type. Again OOP that I won't explain here, I said in previous posts that you should definitely dedicate some time for object oriented programming if you want to understand and create better applications. I can provide you one link about it here: CSharp Generic Classes  for a quick review what is a Generic class.

3. Then we have a method that is called Seed. This method takes the database context object as an input parameter and the code in the method will use that object to add new entities to the database. Our object is BlogContext Class. Remember when I told you a bit of objects when I was talking about the classes? This is that kind of an object. A class is one object! It is also good to know that for each entity type, the code creates a collection of new entities, adds them to the appropriate DbSet property and then saves the changes to the database.

4. We then have two variables that are just reserved as a location in memory and they are a type of List. One variable takes class Blog as a type and we add one object of Blog class with writing "new Blog{}" and inside of it set the given parameters. For the variable posts, it is the same routine, we just add more objects of class Post as we want to have fewer posts to resemble a real post. One thing though is that BlogID is navigational property so we are setting it to number 1 as that is what our BlogID is set to be from blogs variable.

5. After each of this variables, we are going trough the each of elements of the variable, since they are type of List, using ForEach for our variable which is actually LinQ technology, (also something you should read about how it works), where we add each of this element to the BlogContext property.

6. And finally we are saving changes to our BlogContext. You don't need to type after each variable SaveChanges(), but it is good to do so in case you get an error and then you can easily find which one is making you problems.

7. To Summarize what we have just done. We have created two classes. One is BlogContext that creates our database and tables. And another one is BlogInitializier that fills our database with some data.

8. There is one last thing we need to do and that is to set our Web.config file to read this Context and Intializer class. So go to your Web.config file and find the line <appSettings>


If you did then add right above that line this lines of code:

==============================================================
 <connectionStrings>
  <add name="BlogContext" connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\dusha_000\Documents\BlogDataBase.mdf;Integrated Security=True;" providerName="System.Data.SqlClient" />
 </connectionStrings>

==============================================================

What you say with this code is that you are adding a ConnectionString to our application. You are adding one that the name of that string connection is "BlogContext" and if you remember you wrote the name in the BlogContext class inside the :base() brackets. Then you specify the ConnectionString.

Now, you should check what is your connectionString. The best way to do that is to go to your Server Explorer tab, or well anywhere where you have the database, click on the Database, not tables, but the Databse, and in the properties you should see the ConnectionString. Like on the picture:

Connection String

Copy that DataSource and write it inside the connectionString="" attribute, because your connection string is different then mine. However, if you leave this attribute blank and just write "Data Source=(LocalDb)\v11.0;Initial Catalog=SomeName;Integrated Security=SSPI;" you don't need to specify the string, but the Entity Framework should make the database with SomeName you have provided. Unfortunately, this didn't work on my PC, I think I have some issue with local accounts and I can't get to connect with this kind of database creation, but creating the database and then copy-pasting its connectionString is doing the trick.

And finally proivedName as you see it in my code.

To tell Entity Framework to use your Context and Intilaizer classes, you need to add an element to the <entityFramework> element in the Web.Config file.

So find the <entityFramework> and add right under that line following:

=============================================================

 <contexts>
      <context type="BlogProject_Dusan_MVC.Models.BlogContext, BlogProject_Dusan_MVC">
        <databaseInitializer type="BlogProject_Dusan_MVC.Models.BlogInitializer, BlogProject_Dusan_MVC" />
      </context>
 </contexts>

============================================================


It is quite straight forward - you add a <context type> element, where your type is the <namespace.class> of your BlogContext, so if you don't know what your namespace is, you can go to your class and copy paste it here and then just add .BlogContext or class name, and then the name of the project.

Inside the <context type> element you are adding a <databaseIntiializer> element, that you do pretty much the same except different name for the class.

So to clear things up, if it is not already clear, we add elements to Web.config file to tell our project to read specific paths that tell our project, where to read things necessary for our project to work properly. In this case Entity Framework is reading what it needs to create in our database and where is that database, by reading our connectionString.

And that would end our Code First Database Creation that had to take 3 parts in doing so. I know it is a dull thing...I mean...it is a lot of following the rules of what you must write to make Entity Framework read the things properly. The funniest part is that you don't even have to do it this way... Meaning in Code First approach.

You can if you are used to use queries in Databases make the tables that way, and then you can create Controllers by reading that database, using Entity Framework. My goal in using this Code First is to show in some way how Models are related to the database.


In the next post, you will finally see how our page for what we have in the database will look like. When you think of saying that this is supposed to be Small and Simple Blog...it doesn't really look like now does it? It will in the next post!


Friday, May 22, 2015

Building a Blog - Pt2. Building a Database, Models and Entity Framework

I had some killing headache last few days, not sure is it caffeine or too much Coke or what is it, also there was an official event for getting my diploma but back in business! Now... To execute an... Pt.2 of Buliding Database for our Blog project using Code First approach. It will be quite lengthy as code will take a lot of place, so flush ice cold water into your eyes, make sure you avoid the rest of the face and let's go!

I want to use Code first approach as, I believe, it can bring a bit more understanding to what is going on when working with Models in our database in MVC. So let's create our models.

Since I said in the beginning of this blog that we are thinking for now only about Blog name and Posts. Let's create a Model for our Blog name.

Now you might wonder "why Model for a Blog name?" and... It's more about having a Model for multiple Blogs. Because you don't necessarily want to have only one Blog about anything. Some people have multiple blogs, if you are using Google's Blogger, you can see that you can make few Blogs not just one. So in that way we need a Model for our Blog. Since Models are presenting database, that is our purpose for the Blog Model. To have a table in a database that will remember the Names of the Blogs we want to have. I just say this so you can see the bigger picture, I am still going to stick to one blog for now. But it is good practice never the less to do so.

In Visual Studio 2013, on the project you have created, in the Solution Explorer, and then Models folder, right-click and Add a new Class. Call it a Blog. You should have now something like this:


============================================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BlogProject_Dusan_MVC.Models
{
    public class Blog
    {

    }
}

=============================================


If so that's good. So the next question is, what our Blog model needs to have? An identification number which is also a primary key for our database table, and a Name. When I say what our Blog model needs to have it is the Database Table I think of. So we will add these properties:


=============================================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BlogProject_Dusan_MVC.Models
{
    public class Blog
    {
        public int BlogID { get; set; }
        public string Name { get; set; }

    }
}


=============================================

That is all I want for Blog Model to have. Because what I am thinking now is what my next Model or Database Table need to have and that is Post model. I need to know that, when I create a Post as you would do in any Blog, I need to know to which Blog it is related to. So first create a new Class in Model folder in Visual Studio and call it Post:


=============================================

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BlogProject_Dusan_MVC.Models
{
    public class Post
    {


    }
}


=============================================

Same as Blog class just it is called the Post. Thinking of what the Model or Database table should have we have, again, ID that will make Primary key in our table in the database, then Title and Content. But we also have a Foreign key or virtual property that tells to this model, that one property is related to the other Model's property:

=============================================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;



namespace BlogProject_Dusan_MVC.Models
{
    public class Post
    {
        public int PostID { get; set; }
        public string Title { get; set; }
        public string Content { get; set; }
        public int BlogID { get; set; }

        public virtual Blog Blog { get; set; }

    }
}

=============================================


Now you might wonder "how does this tell to what or whom, that this virtual property, and god knows what virtual is, is related to the Blog model?!". This is where the Entity Framework comes in. And what you need to know for "virtual" in Model, is that, it is being used to say to Entity Framework, that property BlogID has a navigation property, which in this case is virtual Blog property.


So the question arises "where do I get this Entity Framework thing!?" you install it as additional package to your Project. To do so go: Tools > NuGet Package Manager > Package Manager Console

Once you have Package Console up, type in:

Install-Package EntityFramework

You should get something like this:

Installing Entity Framework in Package Manager Console

So Entity Framework is a package that you install for your project in order to create Databases. Whether that is Code First, using Entity Framework Designer. You can also use it if you have an already existing database. You can read more about it here - Entity Framework

All right. We now have two models. Blog and Post and your Models folder in your Project should look like this:

Class files that represent Models in the Model Folder of Visual Studio Project

But we just have those two models that just stand there, one of them has something that says something to some guy called Entity Framework, but unfortunately, nothing would happen if we just simply start the application. Because our Database is yet to be created. However, we have to say to Entity Framework to create Database as well. It won't create a database on its own.

But to not make too much info at once and not too much reading at the same time, I will have to write that in another post. It will be probably the final part of creating the database for our Small and Simple Blog.


Friday, May 15, 2015

Building a Blog - Pt1 Builiding a Database (MVC, Models and Classes)

In the previous two posts, I've written about setting the Git on the Github.com and then connecting to it using Visual Studio Express 2013 for the Web. If you are on this post first time, I'd suggest you to read the very first post about Building a Blog, I have written, so you can get more picture of what is this all about.

In this post I have decided to make it in two parts, where in this part or the Pt1 I will say a bit more what MVC is and what Classes are as we will need them for Pt2.

MVC

I guess it is a good time now to explain a bit about what MVC is. MVC stands for Model, View and Controller. They together make a software architectural pattern for implementing user interfaces called MVC.

View - is what the end user will see. Meaning the HTML page or in our case CSHTML. You can think of View as any other HTML page. Meaning you can use CSS styles to it, Javascript, Jquery and all other cool stuff. Purpose of View is to present data that is stored in the Model, to the user.

Controller - is what controls the data between the View and the Model. Say you want to get data from the View stored in the database, or data from the database to the view, the Controller is where you do the POST and GET. Or any other logic you need to manipulate the data. And by database I mean model.

Model - How to put this and to not confuse you because words like "business logic" and "passive" to me, make confusion, because for me logic is being made by the Controller, and Model holds the data so I don't get that someone can write business logic and logics at all when speaking about Model of MVC architecture. For now I can say this. Model stands for the data. So you should think of it that if you have any data (like database data), Model that you have made, will fetch that data from the database when called upon.

In short: Model stands for the data,  the View represents how the Model is visualized and Controller manipulates the state of the Model.

I strongly suggest you if you want to read in more details what MVC is to do so. I am writing here basics and trying to make things the way I have understood them. And finally a diagram to help out understand it as much as possible:

MVC Workflow


Back to real deal. Since I want, for now, to make a Blog that has Posts, I need to make Models for that. Blog model and Posts model. You should know that there is a different approach in doing this in MVC, and I will be using Code first approach, there is also Database First approach, but I will use Code first as it is easier for me to set database that way. Even though I usually do database first, I want to use Code first for this purpose as I don't do it usually simply because I want to understand it that way as well. So personal preference, if you are already used to the database first that is okay and you can do that approach as well, but I will stick to Code First as it might be more appealing to new programmers.

Classes

So... Let's create a new Class in our Model folder. But! I can't go to that step yet as I need to give an explanation what a Class is. That is why I wanted to make this Pt.1 of Database building as there is few things needed to be understood before actually making that first Model. Sure, you can skip this if you already know what a Class is. This will be anyhow very basic for now.


When I first time heard about Class, I've been told "it is like real life object" and it is also one of many things that gave me a headache. Because, after they told me "it is like a House" I was like "really...?" and then they start saying "house has a door and windows, furniture" and I go again like Mental Expression - because they keep telling what the House, as a building have, and don't make a connection to what it has to do with Class in a programming language! So I'll try to explain it the way I understood it after a couple of projects dealing with them. I have also to say that Classes are fundamental in Object-Oriented Programming.

You can indeed think of a Class like an object, but I'd rather say first - think of it as an object you see on your screen. Let's say you have a webpage. It provides some text for users to read, but you want on that webpage to add... A basket. So basket is an object right? I mean you can imagine it, you saw some people carry baskets in the shop most likely... So if you are getting the picture you have an object that represents a basket. So what do we want that basket to be used for? Since I already said it is a basket on the webpage, let it be a shopping basket for users to put some products into it. So we have an object that is shopping basket. Therefore, our class is a shopping basket. You define classes as this:

public class ShoppingBasket
{

}

In order for our class, or basket to receive something, you need to give it properties. You can't in programing expect that anything will work if you didn't write to the program to do so. So even if we created our class, it won't do anything until we tell that class what it needs to have. So our basket should have something that identifies which basket it is. Like you don't have one basket in a shop that 15 people use, it would lead to riots... Not to mention if it is a wedding dress shop. So you have 15 different baskets for each person. But since in programming, we need to track shopping baskets and who is using them, we need to give them some identification. So we give them an ID number:

public class ShoppingBasket
{
    private int ID { get; set; }    
}


NOTE: I would really want to explain what is private, and what does get; and set; do, but this post would be much longer than it is aimed to be. I must point out, private is right of access in object oriented programing of the given property, in our case ID property. If you really want to know OOP (object oriented programming) then you should dedicate some time to understand it. For now I will stick to what is needed for our Blog Project. 


What else do we need to know about our basket object? Who is using it right? I mean in real life shop you won't go to the person and say "give me your wallet so I can check your name and know who is using my baskets!" and do it with a bandana on your head. That is why for me comparing classes to the real life objects don't really make sense to begin explaining with and about. Instead, since we are thinking about the object on the screen, that represents a shopping basket on the webpage for users that want to buy something, we need to know which users are using the basket, so that later on when they bring their basket on a check out, we know who is the person buying and which products. Even in real life shop, when the basket is getting to the cashier it doesn't arrive there by itself. Usually has a human companion. So having that in mind, we add properties like these:

public class ShoppingBasket
{
    private int ID { get; set; }
    private string UserName { get; set; }
    private string Products { get; set; }
}


Okey, so this far what we have done, is far from perfect and what class actually is but you do have a starting point and this is mostly what we will need for now. There are a lot of things in order to our class serve the purpose it should, like List of  products and then making the class being type of List and many other things that are all most OOP. And I don't want to confuse you about that nor make you feel you waste your time anymore, my point was to show you a very very basic understanding of what a Class is in programming. When it comes to comparing Classes of real life objects, it is true you can think of real things as programming objects. For example, if you are making an application that is being used on a bus station? So you would need to think that Bus is an object, it has this and that amount of seats, then, that this and that Bus is driving to this and that town and such, but I didn't want to talk about this way of seeing objects before you see the purpose of it in the programming.

In the next post we will use classes you've just read about to make our Models that will store data to the database. Not the ShoppingBasket it self, but the Blog and Post Class.