Showing posts with label Code First. Show all posts
Showing posts with label Code First. Show all posts

Thursday, July 19, 2012

[C# and EF] Tutorial: Entity Framework Code First Migrations 2/2

This second part of the series shows how to activate EF Code First Migrations and either handle them manually in code or – even more interesting - letting EF handle them automatically for you.

Manual Code-based EF Code First Migrations

The first possibility is to handle those changes manually from within your code. Here is how that works.

  • Open the Package Manager Console from the Tools menu within Visual Studio 2012.

image_thumb2

  • Activate the manual EF Migration features by entering the command “Enable-Migrations”.

image_thumb4

  • This adds a new folder Migrations and also the auto-generated classes Configuration.cs  and [SOMEDATE]_InitialCreate.cs to your project.

image_thumb5

  • The Configuration.cs class allows you to configure the EF Code First Migrations options and seed data after migration (very useful for testing purposes during development).

image

  • The other class contains all the code necessary to create the database (Up) and also drop it (Down) if necessary.

image

  • Here is an example of what can be found in the Up() method.

image

  • Here is an example of what can be found in the Down() method.

image

From here you may start to implement you own code in C# for handling EF Code First and database schema changes.

Automatic EF Code First Migrations

Being able to handle database schema changes related to EF Code First changes from C# code is great, you won’t need to be an expert of database development anymore. But you still need to know what to change and you still need to allocate some time for it.

What if there would be a fully automated way of handling those changes without any effort? Well there is and you just have to activate it. Here is how that works.

  • Open the Package Manager Console from the Tools menu within Visual Studio 2012.

image_thumb2

  • Activate the automatic EF Migration features by entering the command “Enable-Migrations -EnableAutomaticMigrations”.
  • If you try that on a project where you have already activated the manual EF Code First features, you just need to delete the Migrations folder first.

image

  • If you look into the Configuration.cs file you will see that the flag to activate automatic migrations is now enabled.

image_thumb7

  • When you now change the EF Code First model as explained in the first post of the series, you may start the automatic migration of the database via the Package Manager console by entering “Update-Database”.

image

  • And you see that the automatic migration was not applied because it would result in data loss. By default it is not allowed to apply automatic migrations if there is data loss implied. This is a security feature to not accidently delete important data from the database. Mind that you may revert back to an old database schema but you won’t get back deleted data!
  • So now it is up to you to either review the changes or allow automatic migrations if there is data loss (really use this with percaution!!).
  • To allow data loss you just set the flag AutomaticMigrationsDataLossAllowed to true in the Configuration constructor.

image

  • When you restart the automatic migration of the database via the Package Manager console by entering “Update-Database” (you may want to add the “–Verbose” flag) you see all the changes that were applied.

image

  • You can now use your application as expected. The modifications in the database reflect the EF Code First model changes.

Share/Save/Bookmark

[C# and EF] Tutorial: Entity Framework Code First Migrations 1/2

I showed you how to use the Entity Framework Code First approach in one of my last blog posts. This approach is very useful if you want to begin with the implementation and there is no database yet. You want to concentrate on the code and not worry about the database at all, therefore letting Entity Framework auto-generate the database for you.

This is especially interesting for developers not having too much experience in database development or in cases where you have to deliver very quickly and you just don’t want to bother with database design.

The problem : Lack of handling Code First model changes in the DB

Code First works very well and is very easy to use. But it lacks an important feature as I have already pointed out in one of my other blog posts – the handling of database schema changes (add/delete/modify columns, add/delete/modify data types, add/delete/modify constraints, etc…) related to EF Code First model changes .

When you change the underlying EF Code First model expressed in your code (via POCO classes for example) and/or its restrictions you either have to re-create the whole database, meaning that all your data gets lost in the process (not acceptable in production use), or code the database changes manually via SQL upgrade scripts.

In this case the developer still needs to have good database development skills and spent time to create, test and execute the upgrade scripts. This is a tedious task, which the new version of Entity Framework 5.0 integrated in .NET 4.5  is going to greatly simplify and automate.

The solution: Code First Migrations

Microsoft heard the customer requests concerning this problem and added what is called Entity Framework Migrations. It is very easy to activate, and though not perfect, serves very well for applying necessary database schema changes if you work with EF Code First.

Let me show you how it works by providing an example in Visual Studio 2012.

  • Create a new project (for the example a console project but you may as well use any other type of project).

image

  • Now do a right click on the project in the Solution Explorer and select to manage the NuGet packages for it.

image

  • In the Nuget packages window search for Entity Framework and select version 5.0 (currently as a release candidate, this won’t be necessary in the future since it will be fully integrated in .NET 4.5).

image

  • This will allow you to use Code First and do an example implementation : a POCO class Person.
  • When you run your application and use the DataContext, the database and all its columns and constraints get automatically generated. Everything works fine and your application works as expected.

image

  • Now you get an application change request and you decide to change the EF Code First model by changing the POCO class.

image

  • But if you try to change the underlying POCO classes of an already generated database and execute your application, you will get the following exception.

image

  • This is the expected behavior since the new EF Code First Migrations features are not activated by default. You have to activate them manually and configure them according to your needs.
  • To do this open the Package Manager Console from the Tools menu within Visual Studio 2012 and activate the EF Code First Migration features from there.

image

In the next part of the series I am going to explain how to activate either the manual or the automatic features of EF Code First Migrations so stay tuned.


Share/Save/Bookmark

Monday, October 17, 2011

[Tutorial] Code First with Entity Framework 4.1
Part5: Concurrency Management & Conclusion

Assuring the consistence and coherence of data in the database is a very important topic. Concurrency problems come up when multiple source (clients, systems, etc…) try to modify data at the same time.Your application must be able to choose whether to accept or reject any data changes that arrive simultaneously.

Simultaneous execution of transactions must provide the same results as sequential execution of those same transactions.If you achieve this goal then your system is well prepared for correct concurrency handling.

Entity Framework 4.1 includes a very complete concurrency approach. The DbContext class that we already saw before allows for efficient concurrency handling.

First Wins

This resolution strategy defines that the first modification wins if there are concurrency conflicts. All following modifications on the same data are ignored and clients get exceptions that tell them that their transactions did not complete because the data was already changed.

You have to determine which properties might be subject to concurrency problems. You may have properties which do not need any concurrency handling. A property that contains the last modified date might not need to implement any concurrency handling for example.

All properties that must be checked for concurrency need to have the [ConcurrencyCheck] attribute set as shown below:

image

If you don't like using attributes, you may also use the CodeFirst Fluent API on your properties to activate concurrency checking:


image

You have to add concurrency checks only on properties that really need it since this will have some impact on performance within your code. The more properties with activated concurrency checks you have the worse your performance might be depending on your implementation !

image

In the example above we retrieve a manager object from the database, store it in memory and change some property values (but only in memory). We then change some values on the same data directly in the database to simulate concurrency as if two clients did modifications at the same time.

When we call the SaveChanges() method you will see that we get an exception of type DbUpdateConcurrencyException. This is where you need to add your custom concurrency conflict resolution logic. In this example we decided to guard the first modification (First Wins). In the last step we update the context in memory with the data that was changed in the database via ex.GetEntry(context).Reload().

Last Wins

This is the default resolution strategy of EF 4.1 in case of concurrency conflicts. It defines that the last modification wins if there are concurrency conflicts. All previous modifications on the same data are overwritten. Clients only get informed if they use the [ConcurrencyCheck] attribute, some kind of log, some event or other treatment.

image

The example above shows how to implement a Last Wins approach. If there are exceptions due to concurrency conflicts we store the new initial value in the context thus synchronizing with the source. We then retry saving the data until it is saved to the database and the processing is successfully completed.

Conclusion

I hope this tutorial gave you a first insight on the new features of EF 4.1 which are quite powerful even for code purists. With the new features presented in this tutorial EF becomes one of the most complete products on the ORM market. Today, it is the only product that proposes all 3 approaches
CodeFirst, Database First and Model First at the same time.

Some features are missing like auto-synchronization of the database if the class structure changes and stored procedure integration but they will be added in the next weeks / months.

Share/Save/Bookmark

Monday, August 1, 2011

[Tutorial] Code First with Entity Framework 4.1
Part4: Data Audit

All properties within objects managed by the Entity Framework can be audited. This is very helpful if you need to display changes to objects before saving them, cancel modifications by resetting the current value with the initial value or handling concurrency problems.

Entity Framework 4.1 permits accessing the following property versions of an entity:

  • Database Value
  • Original Value
  • Current Value

image

When executing the code above the different values for the Name property of the Manager class are displayed.

image

As you see, adding audit functionality to your applications is really quick to do, Entity Framework 4.1 contains already everything necessary to implement it very easily.


Share/Save/Bookmark

Wednesday, July 27, 2011

[Tutorial] Code First with Entity Framework 4.1
Part3: Data Validation

Data validation is a very important subject when developing applications. You have to assure good quality and high integrity of your data for being able to exploit it correctly. You need to avoid storing any corrupt, incomplete or wrong data in your database which will most certainly lead to misbehavior within your applications.

The following example shows how to implement a constraint on the Name property (required / string length between 5 and 20 characters) via Data Annotations.

image

Validation is automatically done when calling the Save method to persist any changes applied to your objects in memory. But you may as well do it before by calling the GetValidationErrors method.

image

Lets say when the code above is executed it will fail due to validation errors. In this case error messages will be displayed for each constraint that was not respected. In our example we defined that the Name property should have a minimum string length of 5 characters, but the property only contains 4 characters. Since we did not define a specific error message, a generic error message will be displayed for this validation error.

image 

There are multiple Data Annotations that allow for type validation, format validation, regular expression matching, etc….


Share/Save/Bookmark

Tuesday, July 26, 2011

[Tutorial] Code First with Entity Framework 4.1
Part2: Data Annotations & Code First Fluent API

The new version of Entity Framework supports the usage of Data Annotations. Data Annotations are used for validation purposes and also for mapping definitions between code and columns in the database.

All annotations are implemented as attributes which can be found in the System.ComponentModel.DataAnnotations  namespace (same attributes that are used for ASP.NET MVC validation purposes).

Common attributes:

  • [Key] – Column(s) that define the Primary Key in the database table
  • [StringLength] – Minimal and maximal string length (only used for validation purposes not as database constraints)
  • [MaxLength] – Can be used instead of [StringLength] to just define the maximal string length of a column
  • [ConcurrencyCheck] – Flag that indicates that concurrency checks are activated for the column 
  • [Required] – Flag that indicates that a value is required for the column (column is flagged as not null)
  • [Timestamp] – Flag on time stamp columns which is used for concurrency checks
  • [Column] – Specify the name of a column (default property name), can also be used to define the column position
  • [Table] – Specify the name of a table (default class name)
  • [DatabaseGenerated] – Flag that indicates that the value is filled by the database (possible values are Computed, Identity, None)
  • [NotMapped] – Is used to define a property in the class that does not get generated in the database.
  • [ForeignKey] and [InverseProperty] – Column(s) that are defined as Foreign Keys

Following an example for the usage of Data Annotations that was applied to our company domain. The Manager class does not currently contain any properties that could automatically be identified as primary key.

By adding the [Key] attribute to the ManagerCode property you define that this property should act as primary key. You furthermore add a concurrency check as well as a minimum and maximum length setting for the Name property.

image

In the following example we add a required constraint to the Department class by applying the [Required] Data Annotation to the Name property.

image

Data Annotations are definitely easy to use but it  is preferable to use a programmatic approach that provides much more flexibility.  This approach is based on the Code First Fluent API.

You have to implement the OnModelCreating method within the derived CompanyContext class. Then you define your constraints applicable to your domain within this method programmatically.

image

When using this approach you may even describe relations between tables and columns. The following code example defines that the Manager entity contains a Department entity. The key that relates both is the DepartmentId.  If the Manager entity is deleted then the corresponding Department must also be deleted  (CascadeOnDelete).

image


Share/Save/Bookmark

Monday, July 25, 2011

[Tutorial] Code First with Entity Framework 4.1
Part1: Introduction to the Code First approach

This tutorial introduces the new functionalities that were added to Entity Framework 4.1. It shows the differences between the approaches and acts as an introduction to these new features.

Database First & Model First

The Database First approach is interesting when the database already exists. You use Visual Studio and the Entity Framework Designer to generate the C# and VB.NET classes which reflect the existing database model.

You may then change relations and structures using the Designer (or the XML mapping files) to further optimize the model. The priority is the database - the code and the model are only secondary.

The Model First approach is important when you begin from scratch. You start with the entity model and use the Entity Framework Designer to design the relations and the entities.

Then you generate the C# and VB.NET classes and also the database from within Visual Studio. The priority is the model - the code and the database are only secondary.

Code First

When your priority is the code and you want to begin from scratch without any existing schemas or XML mapping files using source code, then the approach is called Code First.

You simply create your domain classes and Entity Framework 4.1 will easily allow to use them with the database and the future model.

You use a context and are able to execute Linq2Entities queries in no time ! You may even take advantage of the change tracking features !

Entity Framework handles all of the background work and manages the interaction with the database. All the classes that are used during runtime are auto-generated.

In this case the configuration is not read from XML files but instead read from the configuration of the DbContext object in memory.

Code First allows:

  • Developing without the need to use the Designer or XML mapping files
  • Defining the objects of the model based on a POCO (Plain Old CLR Objects) approach

Explanation:

  • Design and implement a company domain with Managers, Collaborators and Departments.

Fig1_ClassDiagram

  • Create your classes using a standard object oriented approach and using inheritance when appropriate.
  • Use the POCO approach for your classes where possible.
  • Note that for being able to use the auto-mapping feature for the primary keys you need to have named your class properties like this : [Classname]Id.

image

  • Entity Framework 4.1 allows connecting those POCO classes with the database very easily by using the ObjectContext class (and in particular the DbContext class).

image

  • The last step consists of defining the connection to the database within the web.config or app.config files. Note that EF will search for the connection string that has the same name as the class that was inherited from the DbContext class. You may however define a different name ("CompanyContext" in our example).
image
Share/Save/Bookmark

Wednesday, June 1, 2011

[Publication] Article in French Programmez Magazine on Entity Framework 4.1 and CodeFirst

You can find an article of 5 pages concerning Entity Framework 4.1 and CodeFirst in the French Programmez magazine No.142 written by me and Fathi Bellahcene.

image

First Page and Second Page (low resolution)

Third Page and Fourth Page (low resolution)

Fifth Page (low resolution)

The article is written in French but as always I will write some English articles on my Blog in the next weeks. So stay tuned if you are interested in getting to know the new features of Entity Framework 4.1 and the CodeFirst approach.

You can find the source code here:
http://codefirst.codeplex.com


Share/Save/Bookmark