Types of Entity in Entity Framework

There are two types of Entities in Entity Framework 5.0/6.0: POCO entity and dynamic proxy entity.

  1. POCO Entity (Plain Old CLR Object)
    1. POCO class is the class that doesn’t depend on any framework specific base class. It is like any other normal .net class which is why it is called “Plain Old CLR Objects”.
    2. These POCO entities (also known as persistence-ignorant objects) support most of the same query, insert, update, and delete behaviors as entity types that are generated by the Entity Data Model.
  2. Dynamic Proxy (POCO Proxy)
    1. Dynamic Proxy is a runtime proxy class of POCO entity. It is like a wrapper class of POCO entity. Dynamic proxy entities allow lazy loading and automatic change tracking.
    2. POCO entity should meet the following requirements to become a POCO proxy:
      1. A POCO class must be declared with public access.
      2. A POCO class must not be sealed (NotInheritable in Visual Basic)
  • A POCO class must not be abstract (MustInherit in Visual Basic).
  1. Each navigation property must be declared as public, virtual
  2. Each collection property must be ICollection<T>
  3. ProxyCreationEnabled option must NOT be false (default is true) in context class

By default dynamic proxy is enabled for every entity. However, you can disable dynamic proxy by setting the ProxyCreationEnabled option to false in context class.

context.Configuration.ProxyCreationEnabled = false;

EDM generates POCO entities which satisfy the above requirements for a dynamic proxy by default.

At runtime, type of Student will be System.Data.Entity.DynamicProxies.Student as below:

ef5

Scalar properties:

Scalar properties are properties whose actual values are contained in the entity. For example, Student entity has scalar properties like StudentId and StudentName. These correspond with the Student table columns.

Navigation properties:

Navigation properties are pointers to other related entities. The Student has Standard property as a navigation property that will enable the application to navigate from a Student to related Standard entity.

Advertisements

What is meant by DBContext???

Prior to EntityFramework 4.1, EDM used to generate context classes that were derived from the ObjectContext class. It was a little tricky to work with ObjectContext. DbContext is conceptually similar to ObjectContext. It is a wrapper around ObjectContext which is useful in all the development models: Code First, Model First and Database First.

DbContext is an important part of Entity Framework. It is a bridge between your domain or entity classes and the database.

ef4

DbContext is the primary class that is responsible for interacting with data as object. DbContext is responsible for the following activities:

  • EntitySet: DbContext contains entity set (DbSet<TEntity>) for all the entities which is mapped to DB tables.
  • Querying: DbContext converts LINQ-to-Entities queries to SQL query and send it to the database.
  • Change Tracking: It keeps track of changes that occurred in the entities after it has been querying from the database.
  • Persisting Data: It also performs the Insert, Update and Delete operations to the database, based on what the entity states.
  • Caching: DbContext does first level caching by default. It stores the entities which have been retrieved during the life time of a context class.
  • Manage Relationship: DbContext also manages relationship using CSDL, MSL and SSDL in DB-First or Model-First approach or using fluent API in Code-First approach.

Object Materialization: DbContext converts raw table data into entity objects.

Entity Framework Architecture

ef3

  • EDM (Entity Data Model): EDM consists of three main parts – Conceptual model, Mapping and Storage model.
  • Conceptual Model: The conceptual model contains the model classes and their relationships. This will be independent from your database table design.
  • Storage Model: Storage model is the database design model which includes tables, views, stored procedures, and their relationships and keys.
  • Mapping: Mapping consists of information about how the conceptual model is mapped to the storage model.
  • LINQ to Entities: LINQ to Entities is a query language used to write queries against the object model. It returns entities, which are defined in the conceptual model. You can use your LINQ skills here.
  • Entity SQL: Entity SQL is another query language just like LINQ to Entities. However, it is a little more difficult than L2E and the developer will have to learn it separately.
  • Object Service:Object service is a main entry point for accessing data from the database and to return it back. Object service is responsible for materialization, which is the process of converting data returned from an entity client data provider (next layer) to an entity object structure.
  • Entity Client Data Provider:The main responsibility of this layer is to convert L2E or Entity SQL queries into a SQL query which is understood by the underlying database. It communicates with the ADO.Net data provider which in turn sends or retrieves data from the database.
  • Net Data Provider:This layer communicates with the database using standard ADO.Net.

What is O/RM?

ORM is a tool for storing data from domain objects to relational database like MS SQL Server, in an automated way, without much programming. O/RM includes three main parts: Domain class objects, Relational database objects and Mapping information on how domain objects map to relational database objects (tables, views & storedprocedures). ORM allows us to keep our database design separate from our domain class design. This makes the application maintainable and extendable. It also automates standard CRUD operation (Create, Read, Update & Delete) so that the developer doesn’t need to write it manually.

A typical ORM tool generates classes for the database interaction for your application as shown below

ef2

Entity framework introduction

Writing and managing ADO.Net code for data access is a tedious and monotonous job. Microsoft has provided an O/RM framework called “Entity Framework” to automate database related activities for your application.

Entity framework is an Object/Relational Mapping (O/RM) framework. It is an enhancement to ADO.NET that gives developers an automated mechanism for accessing & storing the data in the database.

Entity framework is useful in three scenarios. First, if you already have existing database or you want to design your database ahead of other parts of the application. Second, you want to focus on your domain classes and then create the database from your domain classes. Third, you want to design your database schema on the visual designer and then create the database and classes.

ef1

Code for the click events in the MVVM with parameters.

While using the MVVM architecture we cannot directly implement the events. To  implement the click and other events we need to implement the ICommand interface. Here we are describing the implementation of the ICommand interface in the real time architecture.


Implementing the ICommand interface to the DelegateCommandBase  abstract class.

public abstract class DelegateCommandBase : ICommand
{
private readonly Func<object, Task> _executeMethod;
private readonly Func<object, bool> _canExecuteMethod;

/// <summary>
/// Creates a new instance of a <see cref=”DelegateCommandBase”/>, specifying both the execute action and the can execute function.
/// </summary>
/// <param name=”executeMethod”>The <see cref=”Action”/> to execute when <see cref=”ICommand.Execute”/> is invoked.</param>
/// <param name=”canExecuteMethod”>The <see cref=”Func{Object,Bool}”/> to invoked when <see cref=”ICommand.CanExecute”/> is invoked.</param>
protected DelegateCommandBase(Action<object> executeMethod, Func<object, bool> canExecuteMethod)
{
if (executeMethod == null || canExecuteMethod == null)
throw new ArgumentNullException(“executeMethod”);

_executeMethod = (arg) => { executeMethod(arg); return Task.Delay(0); };
_canExecuteMethod = canExecuteMethod;
}

/// <summary>
/// Creates a new instance of a <see cref=”DelegateCommandBase”/>, specifying both the Execute action as an awaitable Task and the CanExecute function.
/// </summary>
/// <param name=”executeMethod”>The <see cref=”Func{Object,Task}”/> to execute when <see cref=”ICommand.Execute”/> is invoked.</param>
/// <param name=”canExecuteMethod”>The <see cref=”Func{Object,Bool}”/> to invoked when <see cref=”ICommand.CanExecute”/> is invoked.</param>
protected DelegateCommandBase(Func<object, Task> executeMethod, Func<object, bool> canExecuteMethod)
{
if (executeMethod == null || canExecuteMethod == null)
throw new ArgumentNullException(“executeMethod”);

_executeMethod = executeMethod;
_canExecuteMethod = canExecuteMethod;
}

/// <summary>
/// Raises <see cref=”ICommand.CanExecuteChanged”/> on the UI thread so every
/// command invoker can requery <see cref=”ICommand.CanExecute”/>.
/// </summary>
protected virtual void OnCanExecuteChanged()
{
var handlers = CanExecuteChanged;
if (handlers != null)
{
handlers(this, EventArgs.Empty);
}
}
/// <summary>
/// Raises <see cref=”DelegateCommandBase.CanExecuteChanged”/> on the UI thread so every command invoker
/// can requery to check if the command can execute.
/// <remarks>Note that this will trigger the execution of <see cref=”DelegateCommandBase.CanExecute”/> once for each invoker.</remarks>
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage(“Microsoft.Design”, “CA1030:UseEventsWhereAppropriate”)]
public void RaiseCanExecuteChanged()
{
OnCanExecuteChanged();
}

async void ICommand.Execute(object parameter)
{
await Execute(parameter);
}

bool ICommand.CanExecute(object parameter)
{
return CanExecute(parameter);
}

/// <summary>
/// Executes the command with the provided parameter by invoking the <see cref=”Action{Object}”/> supplied during construction.
/// </summary>
/// <param name=”parameter”></param>
protected async Task Execute(object parameter)
{
await _executeMethod(parameter);
}

/// <summary>
/// Determines if the command can execute with the provided parameter by invoking the <see cref=”Func{Object,Bool}”/> supplied during construction.
/// </summary>
/// <param name=”parameter”>The parameter to use when determining if this command can execute.</param>
/// <returns>Returns <see langword=”true”/> if the command can execute. <see langword=”False”/> otherwise.</returns>
protected bool CanExecute(object parameter)
{
return _canExecuteMethod == null || _canExecuteMethod(parameter);
}

/// <summary>
/// Occurs when changes happen that affect whether or not the command should execute.
/// </summary>
public event EventHandler CanExecuteChanged;

}


Now will use the DelegateCommandBase  abstract class for developing the DelegateCommand class.

/// <summary>
/// An <see cref=”ICommand”/> whose delegates do not take any parameters for <see cref=”Execute”/> and <see cref=”CanExecute”/>.
/// </summary>
/// <seealso cref=”DelegateCommandBase”/>
/// <seealso cref=”DelegateCommand{T}”/>
public class DelegateCommand : DelegateCommandBase
{
/// <summary>
/// Creates a new instance of <see cref=”DelegateCommand”/> with the <see cref=”Action”/> to invoke on execution.
/// </summary>
/// <param name=”executeMethod”>The <see cref=”Action”/> to invoke when <see cref=”ICommand.Execute”/> is called.</param>
public DelegateCommand(Action executeMethod)
: this(executeMethod, () => true)
{
}

/// <summary>
/// Creates a new instance of <see cref=”DelegateCommand”/> with the <see cref=”Action”/> to invoke on execution
/// and a <see langword=”Func” /> to query for determining if the command can execute.
/// </summary>
/// <param name=”executeMethod”>The <see cref=”Action”/> to invoke when <see cref=”ICommand.Execute”/> is called.</param>
/// <param name=”canExecuteMethod”>The <see cref=”Func{TResult}”/> to invoke when <see cref=”ICommand.CanExecute”/> is called</param>
public DelegateCommand(Action executeMethod, Func<bool> canExecuteMethod)
: base((o) => executeMethod(), (o) => canExecuteMethod())
{
if (executeMethod == null && canExecuteMethod == null)
throw new ArgumentNullException(“executeMethod”, “DelegateCommand delegates cannot be null”);
}

/// <summary>
/// Factory method to create a new instance of <see cref=”DelegateCommand”/> from an awaitable handler method.
/// </summary>
/// <param name=”executeMethod”>Delegate to execute when Execute is called on the command.</param>
/// <returns>Constructed instance of <see cref=”DelegateCommand”/></returns>
public static DelegateCommand FromAsyncHandler(Func<Task> executeMethod)
{
return new DelegateCommand(executeMethod);
}

/// <summary>
/// Factory method to create a new instance of <see cref=”DelegateCommand”/> from an awaitable handler method.
/// </summary>
/// <param name=”executeMethod”>Delegate to execute when Execute is called on the command. This can be null to just hook up a CanExecute delegate.</param>
/// <param name=”canExecuteMethod”>Delegate to execute when CanExecute is called on the command. This can be null.</param>
/// <returns>Constructed instance of <see cref=”DelegateCommand”/></returns>
public static DelegateCommand FromAsyncHandler(Func<Task> executeMethod, Func<bool> canExecuteMethod)
{
return new DelegateCommand(executeMethod, canExecuteMethod);
}

///<summary>
/// Executes the command.
///</summary>
public async Task Execute()
{
await Execute(null);
}

/// <summary>
/// Determines if the command can be executed.
/// </summary>
/// <returns>Returns <see langword=”true”/> if the command can execute,otherwise returns <see langword=”false”/>.</returns>
public bool CanExecute()
{
return CanExecute(null);
}

private DelegateCommand(Func<Task> executeMethod)
: this(executeMethod, () => true)
{
}

private DelegateCommand(Func<Task> executeMethod, Func<bool> canExecuteMethod)
: base((o) => executeMethod(), (o) => canExecuteMethod())
{
if (executeMethod == null && canExecuteMethod == null)
throw new ArgumentNullException(“executeMethod”, “DelegateCommand delegates cannot be null”);
}
}


Now will see the implementation in ViewModel. I am taking DashBoardViewModel  as an example

public class DashBoardViewModel
{

private DelegateCommand<string> _saveClick;

public DelegateCommand<string> SaveClick
{
get { return _saveClick; }
}
public DashBoardViewModel()
{
_saveClick = new DelegateCommand<string>(SaveData);

}

private void SaveData(string value)
{
}
}


Now in the xaml code i will add the button like this

<Button Content=”Save” Margin=”10″ CommandParameter=”{Binding Name}” Command=”{Binding Path=DataContext.SaveClick}” />

Publish windows app in C#.net

private void UpdateApp()
{
//log.Debug(“Entering into Update Method”);
UpdateCheckInfo info = null;

if (ApplicationDeployment.IsNetworkDeployed == true)
{
ApplicationDeployment ad = ApplicationDeployment.CurrentDeployment;

//log.Debug(“Application Deployment is executed”);
try
{
//log.Debug(“Check For Update”);

info = ad.CheckForDetailedUpdate();

//log.Debug(“Check info Completed”);
//   log.Debug(“Check For Update Completed”);
}
catch (DeploymentDownloadException dde)
{
//log.Error(dde);
MessageBox.Show(“The new version of the application cannot be downloaded at this time”);
//    + “. \n\nPlease check your network connection”);
return;
}
catch (InvalidDeploymentException ide)
{
//log.Error(ide);
MessageBox.Show(“Cannot check for a new version of the application.”);
return;
}
catch (InvalidOperationException ioe)
{
//log.Error(ioe);
MessageBox.Show(“This application cannot be updated. It is likely not a ClickOnce application”);
return;
}

//Check Patch Update for DB is available or not

Boolean doUpdate = true;
if (info.UpdateAvailable)
{
//log.Debug(“Check For Update available Yes” + info.AvailableVersion.Build.ToString());

System.Windows.Forms.DialogResult dr1 = System.Windows.Forms.MessageBox.Show(“An update is available. Would you like to update the application now?”, “Update Available”, System.Windows.Forms.MessageBoxButtons.OKCancel);
if (!(System.Windows.Forms.DialogResult.OK == dr1))
{
doUpdate = false;
}
else
{
if (info.UpdateAvailable)
{
try
{

ad.Update();
System.Windows.Forms.Application.Restart();

}
catch (DeploymentDownloadException dde)
{
//log.Error(“Error:” + dde.Message);
return;
}
}
else
{
// MessageBox.Show(“No Application Updates are available…”);
}
}
}
else
{
System.Windows.Forms.MessageBox.Show(“No Application Updates are available…”);
}
}
}