Monday, 14 April 2014

Using POCO Classes to create the database using MVC 4 Framework

Using POCO Classes to create the database using MVC 4 Framework

Using POCO Classes to create the database using MVC 4 Framework



POCO means plain old class model , This is known as a code first approach for the Entity Framework. Here I am going to explain how to create the database and the tables using the MVC model classes .

So, let's start , first of all we need to create a MVC4 project for it.

Click on the new project in Visual studio 2012


Now put a name for your MVC4 project  and click on the OK.it will show the MVC 4 project template dialog .


Select Internet application and click on the OK. The Internet application provides all the default setting for MVC4 project . It will create an internet application project for your MVC4 application.



Now right click on the model and add a new class which you want as a table into the database . Here I am creating a class named Country.


Now time to write some code.


I have added two property name CountryId and CountryName which will be columns for the My Country Table. Now Next question in your mind is what will be Table Name . So, by default entity framework creates table with the plural form of your class name. but if you want to specify the table name for your model then you can use the Table attribute as below.
Next step how to specify the primary key. For it you can use the key attribute and for specifying Identity columns you need to set DataGeneration.Identity as below.


 Here we have done with a basic model class for a basic Table . Next we need create a database context class. Add a new class under model as below.


Add the Entity namespace reference and inherit that context class from the DBContext Class as below.


Add the DBSet for your class  as below.


Now we need to specify the connection string in web config which will be used by this class. One thing you need to remember that by default EF assumes that your context class name is the connection string name until you specify it.


So this connection string will be used by EF to create new database named mytestDB under app_data .

Now we need to set the database initializer in Application_Start in global file as below.


We are done with all the configuration . Now the EF don't have any idea about the model classes until we gives it first call. For it we will create a controller and the view but first compile your application once.

Right click on the controller folder and  go to add--> controller . It will show a dialog. select the controller name template  and the data context as below and click on the add button.


It will automatically generate the controller and the views . Now final step run the application and send the first hit to the EF by browsing the Country view.


And we are done. Check the App_Data folder by selecting view all files from the menu.



The EF created the database and the table . WELL DONE

Thursday, 3 April 2014

EF Questions -2

What is Entity Framework?

ADO.NET entity is an ORM (object relational mapping) which creates a higher abstract object model over ADO.NET components. So rather than getting into dataset, datatables, command, and connection objects as shown in the below code, you work on higher level domain objects like customers, suppliers, etc.
DataTable table = adoDs.Tables[0];
for (int j = 0; j < table.Rows.Count; j++)
{
    DataRow row = table.Rows[j];

    // Get the values of the fields
    string CustomerName =
        (string)row["Customername"];
    string CustomerCode =
        (string)row["CustomerCode"];
}
Below is the code for Entity Framework in which we are working on higher level domain objects like customer rather than with base level ADO.NET components (like dataset, datareader, command, connection objects, etc.).
foreach (Customer objCust in obj.Customers)
{}

What are the benefits of using EF?

The main and the only benefit of EF is it auto-generates code for the Model (middle layer), Data Access Layer, and mapping code, thus reducing a lot of development time.

What are the different ways of creating these domain / entity objects?

Entity objects can be created in two ways: from a database structure, or by starting from scratch by creating a model.

What is pluralize and singularize in the Entity Framework dialog box?

“Pluralize” and “Singularize” give meaningful naming conventions to objects. In simple words it says do you want to represent your objects with the below naming convention:
  • One Customer record means “Customer” (singular).
  • Lot of customer records means “Customer’s” (plural, watch the “s”)
If you select the below checkbox, Entity Framework generates a naming convention which adheres to plural and singular coding conventions.

What is the importance of EDMX file in Entity Framework?

EDMX (Entity Data Model XML) is an XML file which contains all the mapping details of how your objects map with SQL tables. The EDMX file is further divided into three sections: CSDL, SSDL, and MSL.

Can you explain CSDL, SSDL and MSL sections in an EDMX file?

  • CSDL (Conceptual Schema definition language) is the conceptual abstraction which is exposed to the application.
  • SSDL (Storage Schema Definition Language) defines the mapping with your RDBMS data structure.
  • MSL (Mapping Schema Language) connects the CSDL and SSDL.
CSDL, SSDL and MSL are actually XML files.
Figure: CSDL, MSL, and SSDL

What are T4 templates?

T4 (Text Template Transformation Toolkit) is a template based code generation engine. You can go and write C# code in T4 templates (.tt is the extension) files and those C# codes execute to generate the file as per the written C# logic.
For instance, the below T4 C# code:
<#@ template language="“C#”" #>
Hello <# Write(”World!”) #> 
Will generate the following C# output:
Hello
World !

What is the importance of T4 in Entity Framework?

T4 files are the heart of EF code generation. The T4 code templates read the EDMX XML file and generate C# behind code. This C# behind code is nothing but your entity and context classes.
If you create a project using VS 2012, you will see the following hierarchy. At the top we have the EDMX file, followed by the TT or T4 file, and then the .CS code file.

How can we read records using Entity Framework classes?

In order to browse through records you can create the object of the context class and inside the context class you will get the records.
For instance, in the below code snippet we are looping through a customer object collection. This customer collection is the output given by the context class CustomermytextEntities.
CustomermytestEntities obj = new CustomermytestEntities();
foreach (Customer objCust in obj.Customers)
{}

How can we add, update, and delete using EF?

Create the object of your entity class, add it to the data context using AddObject method, and then call the SaveChanges method.
CustomermytestEntities obj = new CustomermytestEntities();
Customer objCust = new Customer();
objCust.CustomerCode = "1001";
obj.Customers.AddObject(objCust);
obj.SaveChanges();
If you want to update, select the object, make changes to the object, and call AcceptAllChanges.
CustomermytestEntities objContext = new CustomermytestEntities();
Customer objCustomer = (Customer)objContext.Customers.FirstOrDefault();
objCustomer.CountryCode = "NEP";
objContext.AcceptAllChanges();
If you want to delete, call the DeleteObject method as shown in the below code snippet:
CustomermytestEntities objContext = new CustomermytestEntities();
Customer objCustomer = (Customer)objContext.Customers.FirstOrDefault();
objContext.DeleteObject(objCustomer);

Can you explain lazy loading in a detailed manner?

Lazy loading is a concept where we load objects on demand rather than loading everything in one go. Consider a situation where you have 1 to many relationships between the Customer and Address objects. Now let’s say you are browsing the customer data but you do not want address data to be loaded at that moment. But the time you start accessing the address object you would like to load address data from the database.
Entity Framework has lazy loading behavior by default enabled. For instance, consider the below code. When we are doing a foreach on the Customer object, the Address object is not loaded. But the time you start doing foreach on the address collection, the Address object is loaded from SQL Server by firing SQL queries.
So in simple words, it will fire a separate query for each address record of the customer, which is definitely not good for a large number of records.
MyEntities context = new MyEntities();

var Customers = context.Customers.ToList();

foreach (Customercust in Customers) // In this line no address object loaded
{
     foreach(Address add in cust.Addresses){}// Address object is loaded here
}

How can we turn off lazy loading?

The opposite of lazy loading is eager loading. In eager loading we load the objects beforehand. So the first thing is we need to disable lazy loading by setting LazyLoadingEnabled to false.
context.ContextOptions.LazyLoadingEnabled = false;
Now we have to explicitly tell EF what objects we want to load by using the include function. Below is a simple sample code where we tell EF to load customer as well as address objects by using the include function.
Now the customer object and the related address objects will be loaded in one query rather than multiple queries.
var employees = context.Customers.Include("Addresses").Take(5);

How can we use stored procedures in Entity Framework?

You can use stored procedure mapping details in EDMX as shown in the below figure.
Figure: Specify stored procedures

What are POCO classes in Entity Framework?

POCO means Plain Old C# Object. When EDMX creates classes, they are cluttered with a lot of entity tags. For instance, below is a simple customer class generated using Entity Framework. Many times we would like to use simple .NET classes and integrate them with Entity Framework.
Entity Framework allows this. In other words you can create a simple .NET class and use the entity context object to load your simple .NET classes.
Below is a simple class generated by EF which is cluttered with a lot of EF attributes.
[EdmEntityTypeAttribute(NamespaceName="CustomermytestModel", Name="Customer")]
[Serializable()]
[DataContractAttribute(IsReference=true)]
public partial class Customer : EntityObject
{
    #region Factory Method

    /// <summary>
    /// Create a new Customer object.
    /// </summary>
    /// <param name="id" />Initial value of the Id property.
    /// <param name="customerCode" />Initial value of the CustomerCode property.
    /// <param name="customername" />Initial value of the Customername property.
    public static Customer CreateCustomer(global::System.Int32 id, 
       global::System.String customerCode, global::System.String customername)
    {
        Customer customer = new Customer();
        customer.Id = id;
        customer.CustomerCode = customerCode;
        customer.Customername = customername;
        return customer;
    }

    #endregion
    #region Primitive Properties

How do we implement POCO in Entity Framework?

To implement POCO is a three step process:
  • Go to the designer and set the code generation strategy to NONE. This step means that you would be generating the classes on your own rather than relying on EF auto code generation.
  • Now that we have stopped the auto generation of code, we need to create the domain classes manually. Add a class file and create the domain classes like the Customer class we created.
  • public class Customer
    {
        private string _customerName;
    
        public string CustomerName
        {
            get { return _customerName; }
            set { _customerName = value; }
        }
    
        private int _Customerid;
    
        public int Customerid
        {
            get { return _Customerid; }
            set { _Customerid = value; }
        }
    
    }
  • Write your Context layer code inheriting from ObjectContext. This code you can copy paste from the behind code of EF, also before disabling auto-generation.
  • public partial class Test123Entities : ObjectContext
    { 
        public Test123Entities()
            : base("name=Test123Entities", "Test123Entities")
        {
            this.ContextOptions.LazyLoadingEnabled = true;
            OnContextCreated();
        }
        partial void OnContextCreated();
        public ObjectSet<Customer> Customers
        {
            get
            {
                if ((_Customers == null))
                {
                    _Customers = base.CreateObjectSet<Customer>("Customers");
                }
                return _Customers;
            }
        }
        private ObjectSet<Customer> _Customers;
        public void AddToCustomers(Customer customer)
        {
            base.AddObject("Customers", customer);
        }
    } 
And finally you can use the above code in your client as if you where using EF normally.
Test123Entities oContext = new Test123Entities();
List<Customer> oCustomers = oContext.Customers.ToList<Customer>(); 

In POCO classes do we need EDMX files?

Yes, you will still need EDMX files because the context object reads the EDMX files to do the mapping.

What is Code First approach in Entity Framework?

In Code First approach we avoid working with the Visual Designer of Entity Framework. In other words the EDMX file is excluded from the solution. So you now have complete control over the context class as well as the entity classes.

What is the difference between POCO, Code First, and simple EF approach?

All these three approaches define how much control you want on your Entity Framework code. Entity Framework is an OR mapper, it generates a lot of code, it creates your middle tier (Entity), and Data Access layer (Context).
But a lot of times you want to enjoy the benefits of both worlds, you want the auto-generation part to minimize your development time and you want control on the code so that you can maintain code quality.
Below is the difference table which defines each of the approaches. In simple Entity Framework, everything is auto generated and so you need the EDMX XML file as well. POCO is semi-automatic so you have full control on the entity classes but then the context classes are still generated by the EDMX file.
In Code First, you have complete control on how you can create the entity and context classes. Because you are going to manually create these classes, you do not have dependency on the EDMX XML file. Below is a simple table which shows the cross comparison.
EDMXEntityContext
Simple entity frameworkNeededAutoAuto
POCO approachNeededManualAuto
Code FirstNot NeededManualManual

How can we handle concurrency in Entity Framework?

Note: Before this question, the interviewer can ask you about concurrency and what is pessimistic and optimistic locking. Please do refer to the ADO.NET chapter for those.
In EF, concurrency issue is resolved by using optimistic locking. Please refer to the ADO.NET chapter for what is optimistic locking and pessimistic locking? To implement optimistic locking, right click on the EDMX designer and set the concurrency mode to Fixed, as shown in the below figure.
Now whenever we have concurrency issues you should get an OptimisticConcurrencyException error as shown in the below figure. You can then put a try / catch to handle this situation.

How can we do pessimistic locking in Entity Framework?

We cannot do pessimistic locking using Entity Framework. You can invoke a stored procedure from Entity Framework and do pessimistic locking by setting the isolation level in the stored procedure. But directly, Entity Framework does not support pessimistic locking.

What is client wins and store wins mode in Entity Framework concurrency?

Client wins and store wins are actions which you would like to take when concurrency happens. In store wins / database wins, the data from the server is loaded into your entity objects. Client wins is opposite to stored wins, data from the entity object is saved to the database.
We need to use the Refresh method of the Entity Framework context and provide the RefreshMode enum values. Below is a simple code snippet which executes ClientWins.
Context.Refresh(System.Data.Objects.RefreshMode.ClientWins,Obj);

What are scalar and navigation properties in Entity Framework?

Scalar properties are those where actual values are contained in the entities. For example, in the above customer entity, customername and customerid are scalar properties. Normally a scalar property will map to a database field.
Navigation properties help to navigate from one entity to another entity. For instance, consider the below example in which we have two entities: Customer and Address, and a customer has multiple address objects.
Now we would like to have a facility where at any given moment we would like to browse from a given customer object to the addresses collection and from the address object to the customer.
If you open the Entity Designer, you would notice navigation properties as shown below. The navigation properties are automatically created from the primary and foreign key references.
So now because of those navigation properties, we can browse from the Customer to the Addresses object, look at the below code:
Customer Cust =  oContext.Customers.ToList<Customer>()[0];
// From customer are browsing addresses
List<Address> Addresses = Cust.Addresses.ToList<Address>(); 
You can also do vice versa. In other words, from the Address object, you can reference the Customer object, as shown in the below code.
Address myAddress = Addresses[0];

// From address we can browse customer
Customer cus = myAddress.Customer;

What are complex types in Entity Framework?

There can be situations where you have common properties across entities. For example, consider the below figure where we have Customer and Supplier entities. They have three fields in common: Address1, Address2, and PhoneNo. These fields have been duplicated both in the Customer and Supplier entities.
So to remove these duplicate and redundant fields, we can move them to a common complex type called Address. Complex types group common fields so that they can be reused across entities.
To create a complex type, select the fields which you want to group in a complex type, click on Refactor, and create the complex type. Below is a figure which shows this. Once the complex type is created, you can then reuse the complex type with other entities as well.

What’s the difference between LINQ to SQL and Entity Framework?

  • LINQ to SQL is good for rapid development with SQL Server. EF is for enterprise scenarios and works with SQL Server as well as other databases.
  • LINQ maps directly to tables. One LINQ entity class maps to one table. EF has a conceptual model and that conceptual model maps to the storage model via mappings. So one EF class can map to multiple tables, or one table can map to multiple classes.
  • LINQ is more targeted towards rapid development while EF is for enterprise level where the need is to develop a loosely coupled framework.

What is the difference between DbContext and ObjectContext?

DbContext is a wrapper around ObjectContext, it’s a simplified version of ObjectContext.
As a developer you can start with DbContext as it’s simple to use. When you feel that some of the operations cannot be achieved by DbContext, you can then access ObjectContext from DbContext, as shown in the below code:
((IObjectContextAdapter)dbContext).ObjectContext

EF Questions - 1

http://www.dotnettrace.net/2013/04/using-poco-classes-to-create-database.html
http://pepitosolis.wordpress.com/2013/05/21/entity-framework-code-first-example-in-mvc-4/


1. What is “code first” in relation to Entity framework?

Entity framework uses the process of “code first” that maps database tables to data models. The data models in your .NET project are actually classes that represent the structure of your database tables. This code is used to work with your database, so you don’t need a direct connection to your database in each of your class methods.

2. What is the difference between old ADO .NET and Entity framework coding techniques?

When you used ADO, you connected to the database and had to define a stored procedure or query to retrieve data. With Entity framework, you don’t have to be “blind” when it comes to your tables. ADO did not allow you to get the table structure. With code first, you already have the table structure and Entity framework connects to the database and hides any connection processes. With Entity framework, you’re more aware of the database structure, which helps you avoid any coding mistakes. In addition, if the table structures change, Entity framework updates the data models for you during a refresh.

3. What is LINQ?

Language-Integrated Query (LINQ) is a way to query data without cumbersome stored procedures. Previously, programmers needed to create stored procedures and then call these stored procedures from their code. With Entity framework, you can pull data and query it using language similar to SQL.

4. How is data retrieved?

The difference between older retrieval methods and current Entity framework retrieval methods is that you can now (with Entity) retrieve data as objects. The objects represent the tables (or linked tables) in your database. Instead of iterating through several columns and rows, you just use your class data models. For instance, if you have a table named “users,” you can use the “users” class instead of working through each data set after your query.


5. Can you run SQL statements in an Entity framework environment?

Yes, you can also run SQL query statements. You can use the “ExecuteStoreCommand” method to run SQL on your database. This is usually a secondary option from running simple LINQ on your Entity framework code. You can also run stored procedures from a database.

6. How do you create a database model?

Visual Studio has a database modeler available. You can create a database model from scratch, or you can query the database for the models. If you have a database already, you simply pull the database structures from your code and Entity framework will automatically set up the class data models.

7. Does Entity framework support primary and foreign keys?

Yes, Entity framework supports both types of primary and foreign keys. You can define these in your database tables and import them to your model classes. If you don’t already have a database set up, you can create these keys in your data model classes and their respective data modeling classes.

8. How do you mark a data column as required by the database?

You can “decorate” your data models. The “Required” decoration marks a field as required. Before a user can submit the data to the database, the user must have this field entered. You can also auto-generate required fields in your code, so the code automatically adds the required data.

9. What is lazy loading?

Lazy loading is a way to return only objects that are used. When you query the database model, lazy loading only returns the immediate tables needed by the user. All related tables are returned when they are used. This means you can reserve memory and storage when you work with large programs. It also means that objects are created until you need them, so it makes your program faster.

10. What is eager loading?

Eager loading is the opposite of lazy loading. When you query for objects, eager loading returns all of the objects including the related objects. For instance, when you query a list of customers and orders, eager loading loads all objects including the customers and the orders instead of just what you originally need (customers).

11. What is a navigation property?

A navigation property points to related tables in your database model. For instance, if you have a customer table that relates to the orders table, the navigation property points from the customers table to the orders table. While the primary and foreign keys are physical properties of the table, the navigation properties are a logical part of a data model. When you view the Entity framework model, you can view the navigation properties to better understand the structure of your tables.

12. What is a scalar property in your data model?

A scalar property is similar to a scalar property in the database. A scalar property points to one location in the table.

13. What is a complex data type?

A complex data type occurs when you need to point to another data object from one data object. For instance, if you have several tables that require an address, you can turn those addresses into a table of addresses. You then point your address columns to the new address table, which creates a complex data type. You will likely have complex data types in every .NET Entity framework project, because it makes it easier to relate one table and data model to another without creating cumbersome code.

14. Overall, what is Entity framework?

Entity framework is a type of ORM (object relationship model) that connects classes with database objects. It makes it easier to work with databases and tables without worrying about columns and rows. ORM makes it easier for you to query databases using LINQ, and you do not need to worry about your database connection. Additionally, you can create programs that are unaware of the database and its connection or type (Oracle, SQL Server or MySQL). Entity framework takes care of all of the back-end connection so you can worry about the queries and data.
These are just a few of the common questions you need to know when you go for jobs in the .NET development industry. Entity framework is a comprehensive tool when you want to work with databases in your .NET development platform. You can’t guarantee that any one question will be asked when you go for an interview, but you can prepare for some of the common questions that are regularly asked by interviewers.

15.Will there be any issues adding a table without primary keys to a data model?

Every entity must have a key, even in the case where the entity maps to a view. When you use the Entity Designer to create or update a model, the classes that are generated inherit from EntityObject, which requires EntityKey. So, we have to have a primary key in the table to add it to the data model.

16.How do you truncate a table using entity data model?

Unfortunately Entity Framework doesn't include anything straight forward to handle this. But we can still call a T-SQL statement using entity framework that will still minimizes the developers work. We can call ExecuteStoreCommand() methond on ObjectContext as shown below.
using (var context = new MyTestDbEntities())
{
    context.ExecuteStoreCommand("TRUNCATE table Dummy");
}
17.How do you query in entity model when the result has a join from from different database other than the entity model? E.g.: SELECT t1.c1, t2.c2 FROM table1 AS t1 JOIN table2 t2 ON t1.c1 = t2.c1
As the entity model doesn't support querying from any entity other than the entities defined in Entity Data Model, we have to query aginst the data base using ExecuteStoredQuery of the context. Following code snippet shows how to query when other databases are joined.
string query = "SELECT t1.c1, t2.c2 FROM table1 AS t1 JOIN table2 t2 ON t1.c1 = t2.c1";
using (var context = new SampleEntities())
{
  ObjectResult<DbDataRecord> records = context.ExecuteStoreQuery<DbDataRecord>(query);
  foreach (DbDataRecord record in records)
  {
    //Do whatever you want
  }
}