Friday, 13 February 2015

Manage DataBase table in Code First approach

In Code First Approach When we declare properties in classes and run the application then its automatically create DataBase Tables As we done it in previous tutorial.
Now the problem is that if we change in parameters  and try to run this application then it gives error. So How to handle this problem. In this tutorial we will solve this type of problem.
In earlier tutorial we create a class of employee with some parameters those are define like that
namespace WindowsFormsApplication1
{
   public class Employee
    {
       public int EmployeeId { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public DateTime? DateOfBirth { get; set; }             
    }}
Now i want to add a new properties in this  Employee class as “ EmployeePlace”  then this class will show like that
namespace WindowsFormsApplication1
{
   public class Employee
    {
       public int EmployeeId { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public DateTime? DateOfBirth { get; set; }             
        public string EmployeePlace { get; set; }
    }}
Now if we run this application then this application will give error that database and the properties define in class is not match or not synchronize.
The model backing the 'EmployeeDBContext' context (Parameter changed )has changed since the database was created.
This is because the Employee class has changed since the database was created. It means Database and the modal(Employee.cs class) is not synchronize, To check that is class change or not EF uses __MigrationHistory table that is auto-generated.
_MigrationHistory  is a table created  by Code First Migrations to store information  about migrations applied to the database.

To remove this error, we have to inform to EF that some changes has done. For this we have to add a Global.Asax.
When you open this class then there are some method already predefine methods there we have to give definition. There you add  System.Data.Entity namespace.
Public  Application_Start(object sender , Event Args e) 
{
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<EmployeeDBContext>());
}
You can write it in different way
Public  Application_Start(object sender , Event Args e) 
{
Database.SetInitializer(new DropCreateDatabaseAlways<EmployeeDBContext>());
}



Now you run your application this will run successfully.




Code first approach In Entity frameWork

Code-first approach we have to create custom classes and based on those custom classes entity framework can generate database automatically for us.
POCO :- POCO class is the class which doesn’t depend on any framework specific base class. It is like any other normal .net class that is why it is called “Plain Old CLR Objects” These POCO entities (also known as persistence-ignorant objects) support most of the same LINQ queries as Entity Object derived entities.
In code First approach we doesn’t work on designer.tt(EDMX). You have to write POCOs classes for this as before I explained you about POCO classes. For creating Code First approach in entity framework First you have to install Entity framework as I shown you in earlier tutorial. Go to your nugget package manager and  search on online as entity framework and download.
Example for Code first approach.
We will understand code first approach with an example of an employee where a user able to add employee and update information of an employee. For this first we have to create classes of the properties of employee. After that we will design database.
Add a class there you put these Below  properties those are defined for an employee.
namespace WindowsFormsApplication1
{
  
   public class Employee
    {
       public int EmployeeId { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public DateTime? DateOfBirth { get; set; }    
       
    }

}

Now we have defined properties of employees. Code first approach needed a Context  class .This class is derived from DBContext. DbContext  is a Collection of entities. So when we have to inebriate this class in defined class.
Add a class name is “CodeFirsrApproach.cs”
using System.Data.Entity;

namespace WindowsFormsApplication1
{
    class CodeFirsrApproach : DbContext
    {
// we will tell the context what should be created in the database Add the following line:
        public DbSet<Employee> Employees { get; set; }          

    }
}            
 
DbSet is a collection of entities.
This ensure us to that it will contain the collection of all employee information and table employee will created. Now you check your SQLServer instance and add this below code in programe.cs class
    var person = new Employee
            {
                FirstName = "Munesh",
                LastName = "Sharma",
                DateOfBirth = DateTime.Now
            };
            using (var context = new CodeFirsrApproach())
            {
                context.Employees.Add(person);

                context.SaveChanges();
            }
            Console.Write("Employee information saved");
            Console.ReadLine();
SaveChanges() is a method which automatically save the data. So when you will run this application its automatically save a data in database.
Now you go to your Sql server database there you see will your tables with and fields. There we no need to pass any parameter it automatically create table in local machine.  



 

Model First Approach with Entity Framework

Modal first approach means we can create Entities, relationships, and inheritance hierarchies on the entity.
In the first article i shown you that how to create Entity data modal.
Step(1):  In entity Data Modal for “Modal first approach”  Go to solution explorer and add new item and select Ado.Net entity data modal and give the name for this. After click in add you will see “ entity data Modal wizard” from there you select  Empty EF designer modal.
                                      
Step(2 ): Hare When you will click on finish yow will see a empty screen (.edmx) there you right click and select  “Entity” from Add New Point

Step(3):When you will click on Entity a new screen will popup there you give Entity name and click OK


Step(4): We  can also add properties in the generated entity by right clicking on entity - > Add New -> Scalar property.

Give the name for Scalar property

Same way we can add Entity and association through toolbox. Go to toolbox and select EntityFramework.
Step(5) After creating Entity ,association right click on designer surfer and select “Generate Database from Modal”.

Step(6): When you will click on generate database from modal” you will see a screen there you give the connection name and click on next



After  click on Next DDL database modal will show there you click on finish.

Step(7): After click on finish This will add ModelName.edmx.sql file in the project. You can execute DDL scripts in Visual Studio by opening .sql file -> right click -> Execute.
Now, we  can generate context class and entities by right clicking on the designer and select Add Code Generation Item..

This will add (ModelName).Context.tt and (ModelName).tt with context class and entity classes as shown below.

So in this way, you can design your db model.




POCO classes in Entity FrameWork

POCO :- POCO class is the class which doesn’t depend on any framework specific base class. It is like any other normal .net class that is why it is called “Plain Old CLR Objects” These POCO entities (also known as persistence-ignorant objects) support most of the same LINQ queries as Entity Object derived entities. These classes (POCO classes) implement only the domain business logic of the application.
Some developers use DTOs (Data Transfer Objects) with classes to pass the data b/w layers., Because POCOs are also used to pass data b/w layers ,but they become heavy. So they use DTOs those are also classes.
The main difference b/w DTO and POCO is that DTOs do not contain any methods. They only contain public members. So sending data through DTO is easy because this is lightweight Objects .
The below  code defines a POCO class.



If you want to create POCO classes instead of entity classes or default entity object, then you can create POCO entity classes.
To create POCOs classes first we have to disable auto create classes or auto create code generation, Which generate Context classes entity code in Model1.designer.cs. For disable this code generation right click on model1.edmx(ado.net data modal) and  click on property then you will see   the value of ‘Custom Tool’ As ‘EntityModelCodeGenerator ’ you remove this value.




After removing value of “Custom tool” you will se that in modal1.edmx there is no  Model1.designer.cs class means now we have to create properties (Context and Entities ) so for this we have to create POCOs classes.
Now double click on Modal1.edmx and right click on designer surface and click on Code generation Items. There a screen will open from there you select ‘ADO.NET POCO Entity Generator’ and click ‘Add’.


After click on add button you will see 2 classes one is modal1.context.tt and other is modal1.tt


Model1.Context.tt is a context file and Model1.tt is entities file. You can modify this file if you want to generate your template. Model1.Context.cs file has a context class and .cs files under Model1.tt are entity classes.
Entity classes have all properties as "Virtual". Means that these entities fulfil the requirements of POCO Proxy entities . These entities can be used as POCO entities or POCO Proxy entities. By default it will be behave  as POCO Proxy entities, but you can disable proxy creation by setting  a property "ObjectContext.ContextOptions.ProxyCreationEnabled = false".
Important :
  • If you want to write a  unit test for context then replace ObjectSet<> to IObjectSet<>
  • If you are not able to see ‘ADO.NET POCO Entity Generator’ then you install  NuGet package library.



C# program Selection Sorting

Selection sort is a straightforward sorting algorithm. This algorithm search for the smallest number in the elements array and then swap i...