Pages

C3 Health Services

Visit Official Website 9278982994

Expert Healthcare at Your Doorstep

Showing posts with label Entity Framework. Show all posts
Showing posts with label Entity Framework. Show all posts

Thursday, 25 April 2013

Types of Entities in Entity Framework: EntityObject, POCO, POCO Proxy and Self-Tracking Entities


Types of Entities in Entity Framework: EntityObject, POCO, POCO Proxy and Self-Tracking Entities

There are four types of Entities in Entity Framework: 

1) EntityObject 
2) POCO (Plain Old CLR Object)
3) POCO Proxy 
4) Self-Tracking Entities

EntityObject

By default, the ADO.NET Entity Data Model tools generate EntityObject derived entities. When you work with EntityObject derived types, the object context manages the relationships between your objects, tracks changes as they occur, and supports lazy loading in the most efficient manner. However, the EntityObject derived types have strong dependency on the Entity Framework.

POCO (Plain Old CLR Object)

POCO class is the class which doesn’t depend on any framework unlike EntityObject specific base class. It is like any other normal .net class that is why it is called “Plain Old CLR Objects”. The Entity Framework enables you to use existing .net classes together with the data model without making any modifications to the existing .net classes. These POCO entities (also known as persistence-ignorant objects) support most of the same LINQ queries as EntityObject derived entities.

POCO Proxy

POCO Proxy is a runtime proxy class of POCO entity. POCO entity becomes POCO Proxy entity if it meets certain requirements to enable lazy loading proxy and instant change tracking. It adds some methods at runtime to your POCO class which does instant change tracking and lazy loading stuff. 

POCO entity should meet the following requirement to become POCO proxy:

1. A custom data class must be declared with public access.
2. A custom data class must not be sealed (Not Inheritable in Visual Basic)
3. A custom data class must not be abstract (Must Inherit in Visual Basic).
4. A custom data class must have a public or protected constructor that does not have parameters.
5. The class cannot implement the IEntityWithChangeTracker or IEntityWithRelationships interfaces because the proxy classes implement these interfaces.
6. The ProxyCreationEnabled option must be set to true.
7. Each navigation property must be declared as public, virtual

Difference between POCO and POCO Proxy Classes

Main difference between POCO and POCO Proxy lies in save changes mechanism. POCO entities use Snapshot mechanism. So before saving changes POCO entities, you must use DetechChanges method of ObjectContext to synchronize data with ObjectStateManager. Whereas POCO Proxy entities use instant change tracking. It synchronize with ObjectStateManager as soon as something changes in the POCO Proxy entity. So it’s more efficient than snapshot mechanism and you don’t have to use DetechChanges method of ObjectContext. Thus POCO Proxy has a same functionality as EntityObject.

Self-Tracking Entities

The EntityObject derived entities, POCO, and POCO proxy entities works well in application where the entity objects can be attached to the object context that handles change tracking on single tier. However, in n-tier application, you have to transfer entities to a tier where the object context is not available e.g. Business tier or presentation tier. So how to track changes and report those changes back to the object context? Answer is “self-tracking entities”. Self-tracking entities as its name suggests, can record changes to scalar, complex, and navigation properties on its own. Self-tracking entities do not depend on the Entity Framework so it can be transferred to other tier.  

Self-Tracking entities have additional change tracking functions and it implements IObjectWithChangeTracker and INotifyPropertyChanged interface. It also mark it as DataContract to be used in WCF services.

Contexts and Entities in EDMX File in Entity Framework

Contexts and Entities in EDMX File in Entity Framework

Contexts and Entities in EDMX play a vital role and you must understand the purpose of these. Context contains all the logic for interacting with database and Entities represent database tables. Entites region contain public partial classes and public properties. Lets discuss it in detail:

When you create any EDMX file, follwing files are generated with it.

Model1.edmx
Model1.tt
Model1.Context.tt
Model1.Designer.cs
Model1.edxm.diagram
Model1.Designer.cs

Automatic code is generated in this file which contains context and entities if the "Code Genereation Strategy" is set to Default from None.

Also some points to note for this file

1. Manual changes to this file may cause unexpected behavior in your application.
2. Manual changes to this file will be overwritten if the code is regenerated.


Contexts and Entities in Model1.designer.cs

ObjectContext

If you open Model1.designer.cs, you can see two main regions, Contexts and Entities. expand contexts region. You can see partial class with suffix ‘entities’ and derived from ObjectContext class.

This class represents EntityContainer which you can see from XML view of Model1.edmx or from EDM property window. You can call this as context class.

This class is the primary class for interacting with entity objects and database. An instance of the ObjectContext class encapsulates the connection to the database, metadata that describes the model, and an ObjectStateManager object that tracks objects during create, update, and delete operations.

ObjectSet

Each EntitySet in context class is a type of ObjectSet<> that wraps the entity. e.g. ObjectSet.

EntityType

If you expand ‘Entities’ region, you can see many partial classes that are derived from EntityObject. This classes are EntityTypes of you model.

EntityType is a datatype in the model. You can see each EntityType for your conceptual model in XML. If you expand EntityType node in XML, you can see each properties and its type and other info.

EntityContainer

EntityContainer is a wrapper for EntitySets and AssociationSets. It is critical entry point for querying the model.

EntitySet

EntitySet is a container for EntityType. It is set of same entitytype. You can think it like db table.

AssociationSet

AssociationSet defines the relation between each EntitySet.

Model1.Context.tt is a context template file and Model1.tt is entities template file. 

Model1.tt and Model1.Context.tt templates, generate model entities and context. 

Model1.Context.tt: It produces a strongly typed ObjectContext for the Model1.edmx

Model1.tt: It is responsible for generating a file for each EntityType and ComplexType in the Model1.Context.tt.

Wednesday, 24 April 2013

Scaler and Navigation Properties in ADO.NET Entity Framework


Scaler and Navigation Properties in ADO.NET Entity Framework

Entities in ADO.NET Entity Framework can have two types of properties, Scalar properties and Navigation properties. 

Scalar Properties: Scalar properties are properties whose actual values are contained in the entity. 
Navigation Properties: Navigation properties are pointers to other related entities. Basically it is equivalent to a foreign key relationship in a database. 

Example of Scaler and Navigation Properties:

I will take an example here to make my defination more clear. Suppose there is Student table in database which has columns like StudentID, StudentName and StandardID. There is another table Standard which has StandardID, StandardName columns. Here StandardID is the forieng key. Now lets create and EDMX from these two tables. EDMX will have two entities Student and Standard which will look like following:

EDMX Entity of Student

Student              --Entity Name
-----------
StudentID          --Scaler Property
StudentName   --Scaler Property
StandardID       --Scaler Property
-----------
Standard           --Navigation Property

EDMX Entity of Standard

Standard               --Entity Name
-----------
StandardID           --Scaler Property
StandardName    --Scaler Property
-----------

Student entity has scalar properties e.g. StudentId, StudentName, StandardID. These correspond with the Student table columns.  

The Student has Standard property as navigation property that will enable application to navigate from a Student to related Standard entity. 

Modelling Approaches for Entity Framework: Database First, Model First, Code First


Modelling Approaches for Entity Framework: Database First, Model First, Code First

While working with ADO.NET Entity Framework, you have 3 types of modelling approaches which are:

1. Database First
2. Model First
3. Code First

Lets discuss these Entity Framework modelling approaches in detail.

1. Database First Modelling Approach

When you generate EDMX from existing database, then it is a Database First approach. So in Database First approach, when you add ADO.NET Entity Data Model, you should select ‘Generate from database’ instead of ‘Empty Model’.

2. Model First Modelling Approach

In Model First approach, you create Entities, Relationships, and Inheritance hierarchies directly on the design surface of EDMX. So in Model First approach, when you add ADO.NET Entity Data Model, you should select ‘Empty Model’ instead of ‘Generate from database’.

After creating required entities, associations and inheritance on design surface of the empty model, you can use designer’s context menu option ‘Generate database from model’. It will not generate new database from model. It will only give you DDL to execute in existing database and it is up to you to execute this DDL.

3. Code First Modelling Approach

In Code First approach, you avoid working with visual model designer (EDMX) completely. You write your POCO classes first and then create database from these POCO classes. Developers who follow the path of Domain-Driven Design (DDD) principles, prefer to begin by coding their classes first and then generating the database required to persist their data.  

DbContext and DbSet: There are two new types introduced for Code First approach, DbContext and DbSet. DbContext is a simplified alternative to ObjectContext and is the primary object for interacting with a database using a specific model. DbSet is a simplified alternative to ObjectSet and is used to perform CRUD operations against a specific type from the model in Code First approach.

Wednesday, 17 April 2013

Object Relational Mapping: Frameworks and Advantages

Object Relational Mapping: Frameworks and Advantages

ORM (Object Relational Mapping) wraps your tables or stored procedures in classes in your programming language, so that instead of writing SQL statements to interact with your database, you use methods and properties of objects.

There are a lot of frameworks available for implementing ORM (Object Relational Mapping) in different programming languages.

Based on abstraction, ORM (Object Relational Mapping) manages the mapping details between a set of objects and underlying relational databases, XML repositories or other data sources and sinks, while simultaneously hiding the often changing details of related interfaces from developers and the code they create.

ORM (Object Relational Mapping) hides and encapsulates change in the data source itself, so that when data sources or their APIs change, only ORM needs to change to keep up—not the applications that use ORM to insulate themselves from this kind of effort. This capacity lets developers take advantage of new classes as they become available and also makes it easy to extend ORM-based applications. In many cases, ORM changes can incorporate new technology and capability without requiring changes to the code for related applications.

Example of ORM (Object Relational Mapping)

Lets say you fire following SQL query using traditional way:

String sql = "SELECT ... FROM persons WHERE id = 10";
DbCommand cmd = new DbCommand(connection, sql);
Result res = cmd.Execute();
String name = res[0]["FIRST_NAME"];

ORM enables you to write same logic on the objects and classes like this:

Person p = repository.GetPerson(10);
String name = p.FirstName;

Some frameworks also put a lot of the code in as static methods on the classes themselves, which means you could do something like this instead:

Person p = Person.Get(10);

Some also implement complex query systems, so you could do this:

Person p = Person.Get(Person.Properties.Id == 10);

Advantages of ORM (Object Relational Mapping)

1. You can hide the SQL away from your logic code.

2. ORM has the benefit of allowing you to more easily support more database engines. For instance, MS SQL Server and Oracle has different names on typical functions, and different ways to do calculations with dates, so a query to "get me all persons edited the last 24 hours" might entail different SQL syntax just for those two database engines. This difference can be put away from your logic code.

3. You can focus on writing the logic, instead of getting all the SQL right. The code will typically be more readable as well, since it doesn't contain all the "plumbing" necessary to talk to the database.

ORM (Object Relational Mapping) Frameworks:

In .NET, ADO.NET Entity Framework is the widely used ORM Framework. There is a long list of ORM frameworks supported in different programming languages. You can read this list from wikipedia.

Tuesday, 16 April 2013

Why to use Entity Framework in .NET? Advantages of Entity Framework

Why to use Entity Framework in .NET? Advantages of Entity Framework
 
Entity Framework is an Object Relational Mapping (ORM) Framework for the .NET Framework. Entity Framework  returns the data in your database as an object.
 
Entity Framework is actually written on top of ADO.NET, meaning under this framework, we are still using ADO.NET. So we cannot say that Entity Framework is a replacement of ADO.NET.
 
Entity Framework basically generates business objects and entities according to the database tables.
 
Advantages of Entity Framework: There are lot of reason why should you use entity framework over LinqToSql and ADO.NET.
 
1. Database performance is improved. Updating your EDM based on your DB changes would take less time rather than the conventional methods. Database operations like select, insert, update, delete will work faster as you don't have to hit database again and again as you would be working with objects not with database tables.
 
2. Entity Framework performing basic CRUD (Create, Read, Update, Delete) operations. So most of the time you don't have to write any SQL yourself. When you make any changes to the object, the ORM will usually detect this, and mark the object as 'modified'. When you save all the changes in your ORM to the database, the ORM will automatically generate insert/update/delete statements, based on what you did with the objects.
 
3. Entity Framework works on databases other than Microsoft SQL Server, like Oracle, MySQL etc. While Linq is limited to MS SQL Server. It is easy to add support for another database (like Oracle) as we are programming against a model.
 
4. Easily managing "1 to 1", "1 to many", and "many to many" relationships.
 
5. Ability to have inheritance relationships between entities.

Monday, 15 April 2013

What is the use of persistence layer in any application architecture?

What is the use of persistence layer in any application architecture?
 
Recently, I fell in a .NET project whose architecture was prepared by one of our senior .NET person who is architect here in .NET. I was confused with pesistence layer he had created in the application architecture. I searched it on google but found on consolidated answers from anywhere. At last I came to get help from Stackoverflow .NET experts. I asked following question on stackoverflow and got valuable responses.
 
My question on persistence layer architecture:
 
I have to create an application in which I am asked to create an persistence layer in the application. The application is in .net. I have created business layer and presentation layer but I don't know how and why to create persistence layer.
 
I googled and came to know that persistence layer is used for storing and retrieving data usually from a database.
 
Can anybody explain in detail?
 
Responses I got:
 
Davide Piras Response which I accepted later on:
 
The reason for you to build a DAL ( Data Access Layer ) or any other kind of intermediate layer between database engine and Business / Application logic, is that by adding this layer in the between you isolate the rest / upper layers of your application from the specific database engine / technology you are using right now.
 
This has several advantages, like easier migration to other storage engines, better encapsulation of database logic in a single layer ( easier to replace or modify later depending on how well you have designed your cross-layer interfaces etc...)
 
See my most rated answer here, it is an example about ASP.NET MVC and EF but the structuring of solution and projects is actually technology independent: MVC3 and Entity Framework
 
Also read some articles to better understand this matter, for example: http://www.developerfusion.com/article/84492/net-and-data-persistence/
 
Renan's Response
 
If you're not saving your data somewhere, it won't be there again when your app is opened again. You can save it to a database as you said (SQL, Oracle, PostGRE etc.), or directly to disk (serializing in binary format, or plain text etc.).
 
Using a layer to do that is a good practice. It reduces coupling (i.e. spaghetti code), and makes maintenance much easier.
 
I suggest you read about Hibernate and it's .NET cousin, NHibe
 
Kenneth Garza's Response:
 
Persistance layer otherwise known as a Data Access Layer or other terminology.
 
It seperates the guts of getting and saving the data from the business layer. The reason you do this is so your business logic (the part of the application that does the heavy lifting for your data manipulation) is not tied to a specific type of data source.
 
The data layer will need to be written to be database specific. So if you're using MySQL to access all your data then you will write the dataLayer for that use.
 
If at some point you decide to move to MongoDB, then instead of rewriting your entire application. You can rewrite just the data access parts to get the data from MongoDB. Since the business logic doesnt care how you get the data, only that you do, it and the Presenation layer can remain intact.
 
Hope this helps.
 
Belogix Response:
 
In very simple terms a persistence layer is a way to SAVE and RETRIEVE items that your application uses.
 
A simple example is you have a class that represents a person (name, age and gender). While your application is running this is held in memory. But, say you want that information available if you close and open your application again. Well, you need some way to SAVE that person and then later on RETRIEVE it again. This is where a persistence layer comes in and will write your person somewhere "permanent".
 
That could be a database, a flat file, registry depending on the life-time and requirements etc.
 
In your persistence layers you will perform CRUD (Create, Read, Update, Delete) operations. Often against a database so you would Create a new person (Fred Bloggs). Say they change their name another user of your system might Read the record and change to Fred Miggins and Update the database. That customer then leaves the country so you Delete them.
 
Please refer to stackoverflow page for details.

About the Author

I have more than 10 years of experience in IT industry. Linkedin Profile

I am currently messing up with neural networks in deep learning. I am learning Python, TensorFlow and Keras.

Author: I am an author of a book on deep learning.

Quiz: I run an online quiz on machine learning and deep learning.