Sei sulla pagina 1di 15

Databases

v2013_S

Lesson 11:
ORM via Code First

Contents
Example 1: Installing and Referencing ............................................................................ 2
Example 2: Implementing Domain Classes ...................................................................... 4
Example 3: Implementing the Database Context.............................................................. 8
Example 4: Creating Objects ........................................................................................... 9
Example 5: Generating the Database ............................................................................. 11
Example 6: Performing Queries ..................................................................................... 14

FESB in cooperation with ZORAJA Consulting d.o.o.

Exercises 11: Code First ORM

Example 1: Installing and Referencing


In this exercise you will (optionally) install and reference Entity Framework 4.1 in
your project.
Information about (downloading) Entity Framework 4.1 can be found at:
http://msdn.microsoft.com/en-us/library/gg696172(v=VS.103).aspx
After installing the EntityFramework.dll will be placed in folder:
C:\Program Files (x86)\Microsoft ADO.NET Entity Framework 4.1\Binaries
You will map the following domain classes:

FESB in cooperation with ZORAJA Consulting d.o.o.

2/15

Exercises 11: Code First ORM

Entity Framework (EF) is a Microsoft ORM (Object Relational Mapping)


tool which maps .NET objects to relational databases. The programmers can use the
EF in three approaches:

Model First
In this approach the programmer (designer) using a graphical tool creates a metamodel and from that model generates the (2) domain classes and (3) database
tables.

Database First
In this approach the programmer (designer) generates (1) the meta-model and (2)
domain classes from the database scheme.

Code First
In this approach the programmer creates domain classes and from it generates
(1) the meta-model (which is hidden) and (2) the database tables. You can also
map classes to existing database tables.
In these exercise we will use the Code First approach.

Create a Project
1. Create a C# Library project, named Family in solution CheCosa.
2. Reference the following assemblies:

System.Data.Entity

System.ComponentModel.DataAnnotations

3. Reference EF 4.1, as shown below:

FESB in cooperation with ZORAJA Consulting d.o.o.

3/15

Exercises 11: Code First ORM

Example 2: Implementing Domain Classes


In this exercise you will create domain classes in C#.

Implement Classes
1. Implement class Boss, as shown below:
using System;
public class Boss
{
public int ID { get; set; }
public string Name { get; set; }
public string EMail { get; set; }
public virtual Mafia Mafia { get; set; }
public override string ToString() {
return "[" + ID + " " + Name + " " + EMail + "]" + Mafia;
}
public void GiveOrder() {
Console.WriteLine("Starting operations:");
Mafia.Execute();
}
}

FESB in cooperation with ZORAJA Consulting d.o.o.

4/15

Exercises 11: Code First ORM

2. Implement class Mafia, as shown below:


using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
public class Mafia
{
public int ID { get; set; }
[StringLength(256)]
public string Name { get; set; }
public string Business { get; set; }
public virtual ICollection<Member> Members {get; set;}
public virtual ICollection<Project> Projects { get; set; }
public override string ToString() {
return "(" + ID + " " + Name + " " + Business + ")";
}
public void PrintMembers () {
Console.WriteLine("{0}'s members: ", Name);
foreach (Member m in Members) Console.WriteLine("\t" + m);
}
public void PrintProjects()
{
Console.WriteLine("{0}'s projects: ", Name);
foreach (Project p in Projects) Console.WriteLine("\t" + p);
}
public void Execute()
{
foreach (Project p in Projects)
foreach (Member m in p.Members) m.DoIt();
}
}

FESB in cooperation with ZORAJA Consulting d.o.o.

5/15

Exercises 11: Code First ORM

3. Implement classes Member, Worker, and Manager, as shown below:


using System;
using System.Collections.Generic;
public abstract class Member
{
public int ID { get; set; }
public string Name { get; set; }
public string Speciality { get; set; }
public virtual ICollection<Project> Projects { get; set; }
public override string ToString() {
return "[" + ID + " " + Name + " " + Speciality + "]";
}
public abstract void DoIt ();
}
public class Manager : Member {
public override void DoIt () {
Console.WriteLine ("\tManager {0}: Organized.", Name);
}
}
public class Worker : Member {
public override void DoIt() {
Console.WriteLine("\tWorker {0}: Done.", Name);
}
}

FESB in cooperation with ZORAJA Consulting d.o.o.

6/15

Exercises 11: Code First ORM

4. Implement class Project, as shown below:


using System;
using System.Collections.Generic;
public class Project
{
public int ID { get; set; }
public string Name { get; set; }
public string Domain { get; set; }
public DateTime StartDate { get; set; }
public virtual ICollection<Member> Members { get; set; }
public void PrintMembers()
{
Console.WriteLine("{0}'s members: ", Name);
foreach (Member m in Members)
Console.WriteLine("\t" + m.Name);
}
public override string ToString() {
return "(" + ID + " " + Name + " " + Domain + ") " +
StartDate.DayOfYear;
}
}

FESB in cooperation with ZORAJA Consulting d.o.o.

7/15

Exercises 11: Code First ORM

Example 3: Implementing the Database Context


In this exercise you will inherit from class DbContext to implement mappings from
classes to tables.
The constructor of the context class receives the connection string that is used to
initialize the database.
Without the connection string and annotations EF 4.1 by default makes use of:

convention over configuration


For conventions in code first see:
http://blogs.msdn.com/b/efdesign/archive/2010/06/01/conventions-for-code-first.aspx
Generic class DbSet is used for individual mappings.

Implement Context
1. Implement class FamilyContext, as shown below:
using System.Data.Entity;
public class FamilyContext : DbContext

public FamilyContext (string cs) : base(cs) { }


public
public
public
public

DbSet<Boss> Bosses { get; set; }


DbSet<Mafia> Mafias { get; set; }
DbSet<Member> Members { get; set; }
DbSet<Project> Projects { get; set; }

FESB in cooperation with ZORAJA Consulting d.o.o.

8/15

Exercises 11: Code First ORM

Example 4: Creating Objects


In this exercise you will instantiate objects from the domain classes.

Create a Project
1. Create a C# Console project, named Program in solution CheCosa.
2. Implement class Program, as shown below:
using
using
using
using

System;
System.Collections.Generic;
System.Data.Entity;
System.Linq;

class Program
{
static Boss boss;
static Mafia mafia;
static Member a, b, c, d, e;
static Project bank, casino;
static FamilyContext context;
static
static
static
static

void
void
void
void

Main(string[] args) {
CreateObjects () { }
PrintFamily () { }
ExecuteQueries() { }

3. Add the configuration file App.config, as shown below:


<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="CheCosaDatabase"
providerName="System.Data.SqlClient"
connectionString="Server=(local);
Database=CheCosa;
IntegratedSecurity=True;
Trusted_Connection=true;
MultipleActiveResultSets=True"/>
</connectionStrings>
</configuration>

FESB in cooperation with ZORAJA Consulting d.o.o.

9/15

Exercises 11: Code First ORM

4. Add code to method CreateObjects, as shown below:


boss = new Boss { Name = "Vito", EMail = "1@checosa.com" };
mafia = new Mafia { Name = "Che Cosa", Business = "Top Secret" };
boss.Mafia = mafia;
a
b
c
d
e

=
=
=
=
=

new
new
new
new
new

Manager { Name = "Michael", Speciality = "Team Building" };


Worker { Name = "Sonny", Speciality = "Vaults" };
Worker { Name = "ime", Speciality = "Guns" };
Worker { Name = "Connie", Speciality = "Cars" };
Worker { Name = "Fredo", Speciality = "Cars" };

mafia.Members = new List<Member> { a, b, c, d, e};


bank = new Project { ID = 100, Name = "Dollar", Domain = "Banks",
StartDate = DateTime.Today};
casino = new Project { ID = 200, Name = "Coin", Domain = "Casions",
StartDate = DateTime.Today };
mafia.Projects = new List<Project> { bank, casino };
a.Projects
b.Projects
c.Projects
d.Projects
e.Projects

=
=
=
=
=

new
new
new
new
new

List<Project>
List<Project>
List<Project>
List<Project>
List<Project>

{
{
{
{
{

bank, casino };
bank };
casino };
bank };
casino };

bank.Members = new List<Member> { a, b, d };


casino.Members = new List<Member> { a, c, e };

5. Add code to method PrintFamily, as shown below:


Console.WriteLine(boss);
mafia.PrintMembers();
mafia.PrintProjects();
casino.PrintMembers();
bank.PrintMembers();

FESB in cooperation with ZORAJA Consulting d.o.o.

10/15

Exercises 11: Code First ORM

Example 5: Generating the Database


In this exercise you will generate the database from the domain classes and populate
the tables with objects.
By convention EF 4.1 makes use of:
SQL Server - SQLEXPRESS
Database - the fully qualified name of the context class
Inheritance mapping - Table per Hierarchy (TPH)
...
If you want to change the default behavior you can use:

Connection strings
Data Annotations
The Fluent API
Generate the Database
1. Add code to method PopulateDatabase, as shown below:
context = new FamilyContext ("Name=CheCosaDatabase");
Database.SetInitializer (
new DropCreateDatabaseAlways<FamilyContext>());
context.Bosses.Add(boss);
int noRows = context.SaveChanges();
Console.WriteLine("{0} Rows affected.", noRows);

2. Implement method Main, as shown below:


CreateObjects();
PrintFamily();
boss.GiveOrder();
PopulateTables();
ExecuteQueries();
Console.WriteLine ("Press any key.");
Console.ReadKey();

FESB in cooperation with ZORAJA Consulting d.o.o.

11/15

Exercises 11: Code First ORM

View the Created Database


1. Run the program and in Server Explorer1, add a Connection, as shown below:

2. Enter the following information into the dialog and click OK.

To show Server Explorer press Ctrl+Alt+S

FESB in cooperation with ZORAJA Consulting d.o.o.

12/15

Exercises 11: Code First ORM

3. Create a new data diagram and add all the tables into it.

... and the following schema should be displayed.

FESB in cooperation with ZORAJA Consulting d.o.o.

13/15

Exercises 11: Code First ORM

Example 6: Performing Queries


In this exercise you use LINQ to perform simple queries on the generated database.

Perform the Queries


3. In class Program implement method ExecuteQueries, as shown below:
Console.WriteLine("Queries ....");
var members = from m in context.Members
where m.ID > 1
select m;
foreach (Member m in members) Console.WriteLine(m);
Console.WriteLine("-----");
var member = context.Members.Find(6);
if (member == null) {
member = new Worker { Name = "Tonny", Speciality = "Phones" };
mafia.Members.Add(member);
}
int noRows = context.SaveChanges();
members = from m in context.Members
where m.ID > 1
select m;
foreach (Member m in members) Console.WriteLine(m);

FESB in cooperation with ZORAJA Consulting d.o.o.

14/15

Exercises 11: Code First ORM

Run the Project


1. Build and run the project 2 again and the output similar to the following will
appear:

Delete the connection to the database since it is dropped in the application.

FESB in cooperation with ZORAJA Consulting d.o.o.

15/15

Potrebbero piacerti anche