Browsing:

Tag: Entity

Entity Framework Part 5 Model First : Create a database with the Complex Types.

A cool feature we are gonna try out in the model first architecture of the entity framework are "Complex Types" a container for property values who are not entities, but a collection of fields that are in line in a table row, a set of columns or properties and not necessary tables itself, to keep a nice clean application based model and have your attributes grouped together.

Model First and Complex Types add new features and possibilities:

We are going to build a console app with Entityframework 4 and name it MyShoeShoes. First we add a new item and choose the ADO.NET Data Model. We choose the empty model:

We call the Model shoe.edmx and now we are going to add our first new entity called: 'Shoe' in the Model Browser

Right click-> add a complex type instead of table rows. With Complex Types you can group together specific collections. In the Model browser you see the Complex type, here we add new lines, Add -> Scaler Property- we add extra shoe properties, in this case a group of ShoeTypes; Heels, Sneakers, Boots etc.

Now we have created Complex Types that do not show up in the design surface, that is for entities only.

Now all we have to do is right click the Shoe entity and choose 'add Complex Property' and name it ShoeType and it automatically sets it to the complex type we've just created: ShoeType.

Now we are going to add a hierarchy, which inherits from the Shoe entity with some extra details we want to use with the Shoe entity. We create an entity and set the base type to Shoe. Now remember this model is a ConceptualEntityModel and we can always tweak this in the database later!

Next entity we create is the ShoeDescription and add an association to it on Shoe, so it links to the Shoe table.

Our model is ready: We have Shoe with a grouped ShoeType, so we can index our ShoeTypes on Type-a-Shoe, We created a Shoe Colour Hierarchy to Shoe, Since one ShoeType can have many colours and a table ShoeDescription always has a relation in Shoe.

Maybe you've noticed that our console app gives an error when you try to built the app: "Error 11007:Entity type 'EntityName' is not mapped when Entity is only mapped to function import" No worries! this error will be solved as soon as we build our database, as the database is generated it will create the mappings for you.

We have all the data we need for our application so it's time to generate a database from this model

The next steps are very easy, we are asked to choose a data connection, don't get distracted by the Shoe.dbo line, we choose a "New Connection" since we have built a brand new Model to create a database from. The connection string is created here as well.

Set the connection Properties and name the new database, we call it MyShoeShoes:

The next step generates a dll file, but this is not run automatically,  we need to create the tables in our database. The database dll will be generated by a so called T4 template and can be modified.

When we look into the generated DLL, we see that the associations are created and it sets the ID as primary key, We call this Table per type, it creates the hierarchy Shoecolor as it's own table with a Shoe_ prefix: 'Shoe_Shoecolor' in the database.

We have to manually run this query in the SQLServer, since the RTM is not completed in VS2010 EF4, but this is just a matter of time. Now refresh the MySHoeSHoes database and pop the tables are generated:

We have now created a complete database from a Model we built in Visual Studio with EF4, how cool is that!


Entity Framework from scratch Part 4 EF4 Multi Layered – System.Data.Entity not referenced

As i mentioned in the previous post, there seems to be a problem when you work with Multi layered Solutions in the Entity Framework. You need to add the Entity references to all the solutions in your project, but i found another small problem when creating a web front to your application.
I've built this app with EF4 features with web functionality.

When i debug my code, the database connection works and the table rows are fetched, but my webpage displays an compilation error: CS0012: The type 'System.Data.Objects.DataClasses.EntityObject' is defined in an assembly that is not referenced. You must add a reference assembly to 'System.Data.Entity, version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.

You need to add extra code manualy to your Web.config file directly under the system.web

<configuration>
  <system.web>

copy/paste the following code:

  <compilation debug="true" targetFramework="4.0">
    <assemblies>
      <add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
      <add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
      <add assembly="System.Web.Mvc, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
      <add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
    </assemblies>
  </compilation>

If you built and re-run the the app, the webpage is displayed correctly.


Entity Framework from scratch Part 3 EF4 Database

How to connect your existing database  to a new entity Framework driven app.  I was surprised about the ease of connecting the database to the app. It takes just 5 steps to realise the connection with any available database. EF supports all sorts of databases.

Here we go: First open your project and right click Shoeshoedata

Then we  select Ado.net Entity Data Model and name it Myshoes.edmx

Choose your excisting datamodel

Choose your data Connection, in this case we use the  excisting' Shoe' database

Select which tables (or views)  you'll need for your EF app

and the database is connected to your new EF4 project. See that was easy.

Now the project is ready to use your database.

And now for the Multiple solution config in EF4

Is this yet another famous Microsoft workaround!? Since the new EF4 app couldn’t find his connection string.

We we're looking for a solution to get our App.config to communicate with the console reference. this problem only occurs  when you work with multiple project solutions, he can't seem to find the correct references.

We found out it doesnt work when you just change the .config properties to Copy always, you also need to copy the app.config file to the console app.  as soon as this is done, it works. Maybe there is another solution for this problem, but i have not yet found it.


Entity Framework from scratch Part 2 EF4 release

A lot has happened since the last blog where we introduced the entity framework and tried to explain the possible benefits it could have over the other NoSQL.
Microsoft has released a new EF4 that builds us cleaner code, “Code First Development”

They have kept their eyes out on the other NoSQL movements and learned, In this post we are going to introduce 2 new types, the DbContext and the DbSet that EF4 brought us.
At first I was puzzled as in why two new types, and not just remake the ObjectContext and ObjectSet.
But there is a logica behind this, as you can read on the Msdn blog. They are no replacement, they are just simplified. Now you can always choose to use the more advanced types. DBSet has full compatibility with the excisting EF’s and to switch to the ObjectContext and ObjectSet.

We are going to build a standard console app.
First, make sure you're on .Net version 4, or the entity framework 4 will not work.

Dwnload the new EF4 features here and install them.

Fire up your visual studio and choose the console app, and name it ShoeShoe. Now add a using statement on top of the program.cs

using System.Data.Entity;

Now define the two classes we need for our data, namely ShoeShoe a class that describes the shoes in my closet and second the type of shoes i have collected.

public class ShoeCat
{
    public string ShoeCatId { get; set; }
    public string Name { get; set; }

    public virtual ICollection Shoe { get; set; }
}

public class ShoeShoe
{
    public int ShoeShoeId { get; set; }
    public string Name { get; set; }
    public string CategoryId { get; set; }

    public virtual ShoeCat Category { get; set; }

Now we are gonna add context using the new DbContext DbSet type from EF4

public class ShoeShoeCatalog : DbContext
{
    public DbSet Categories { get; set; }
    public DbSet Products { get; set; }
}

To get your console app to recognize the Dbset statement, we need to add 2 references:
The Microsoft.Data.Entity.CTP
microsoft.data.entity
and the system.data.entity.

this is all the code needed to start the process of storing and retrieving data.

Now let’s put some data in the app and build a program class

class Program
{
    static void Main(string[] args)
    {
        using (var context = new ShoeShoeCatalog())
        {
            var Pump = new ShoeCat { ShoeCatId = "Pump", Name = "Sexy" };
            context.Categories.Add(Pump);
            int recordsAffected = context.SaveChanges();

            Console.WriteLine(
                "Succesfully Saved {0} row(s) to the database, press any key to exit.",
                recordsAffected);

            Console.ReadKey();
        }
    }
}

Now we successfully added shoeshoe data.
This is ofcourse just the beginning of our shoeshoe app, but i hope you are bit more familiar with the 2 new types EF4 has provided us.

Enjoy ! Next we are going to build extra features in ourShoeShoe console application.


Back to basics: Entity Framework from scratch part 1

Let me first introduce to you the Entity Framework, this is an object relational mapping (ORM) framework for the .net Framework

The power of Entity Framework is that you can safely use your data from your database creating a semi virtual object database within your application so changes are not directly in your database.

Using the nosql eliminates the need for converting data to and from the database, as the data is stored in its original object representation and relationships are directly represented, instead of building breath taking views.

Why entity framework, you ask me? After we took so much effort in presenting you the nosql, i find nosql to be a great timesaver, but when it comes to larger amounts of data that needs to be stored, or existing data in a database can soon become to heavy for Nosql.

Let’s say we want to build an application for a animal hospital and collect all our client and list their names, and type of animals and how long they have been a client of ours since we started in 2001.

We have 3 tables: Contact, animal and animaltype and build the following query:

SELECT c.FirstName, e.animalname
FROM Animal e
INNER JOIN Contact c ON e.AnimalID = c.ContactID
WHERE e.Visitrate >= 1 AND e.registerdate >= '2001-01-01'

This is still a small query but you can imagine if you need typical information from the database, the structure can become very heavy. Especially if you are using specific data for one department.

The logical database schemes do not always meet the application needs, for they are often shared for other applications running on the database, like Enterprisesystems. So often the database model does not relate to the application datamodel.

The entity framework contains a datamodel and design and runtime services so you can define your applicationdata and interact, isolate and play with it on abstract level.

In the next part I will give you an example of the use of entity framework