You are on page 1of 5

Entity framework code first approach

 Code First modeling workflow targets a database that doesn’t exist and Code
First will create it.
 It can also be used if you have an empty database and then Code First will
add new tables to it.
 Code First allows you to define your model using C# or VB.Net classes.
 Additional configuration can optionally be performed using attributes on your
classes and properties or by using a fluent API.

define a very simple model using classes.

Class1
public class Student {
public int ID { get; set; }
public string LastName { get; set; }
public string FirstMidName { get; set; }
public DateTime EnrollmentDate { get; set; }

public virtual ICollection<Enrollment> Enrollments { get; set; }


}

Class2

public class Course {


public int CourseID { get; set; }
public string Title { get; set; }
public int Credits { get; set; }

public virtual ICollection<Enrollment> Enrollments { get; set; }


}

Class3

public class Enrollment {


public int EnrollmentID { get; set; }
public int CourseID { get; set; }
public int StudentID { get; set; }
public Grade? Grade { get; set; }

public virtual Course Course { get; set; }


public virtual Student Student { get; set; }
}

public enum Grade {


A, B, C, D, F
}

Create Database Context


public class MyContext : DbContext {
public virtual DbSet<Course> Courses { get; set; }
public virtual DbSet<Enrollment> Enrollments { get; set; }
public virtual DbSet<Student> Students { get; set; }

add some data and then retrieve it. Following is the code in main method.
static void Main(string[] args) {

using (var context = new MyContext()) {


// Create and save a new Students
Console.WriteLine("Adding new students");

var student = new Student {


FirstMidName = "Alain", LastName = "Bomer",
EnrollmentDate = DateTime.Parse(DateTime.Today.ToString())
};

context.Students.Add(student);

var student1 = new Student {


FirstMidName = "Mark", LastName = "Upston",
EnrollmentDate = DateTime.Parse(DateTime.Today.ToString())
};

context.Students.Add(student1);
context.SaveChanges();

// Display all Students from the database


var students = (from s in context.Students
orderby s.FirstMidName select s).ToList<Student>();

Console.WriteLine("Retrieve all Students from the database:");

foreach (var stdnt in students) {


string name = stdnt.FirstMidName + " " + stdnt.LastName;
Console.WriteLine("ID: {0}, Name: {1}", stdnt.ID, name);
}

Console.WriteLine("Press any key to exit...");


Console.ReadKey();
}
}

You can define the base constructor of the context class in the following ways.

 No Parameter
 Database Name
 Connection String Name

If you specify the base constructor of the context class without any parameter as shown in
the above example, then entity framework will create a database in your local
SQLEXPRESS server with a name {Namespace}.{Context class name}.

public class MyContext : DbContext {


public MyContext() : base() {}
public virtual DbSet<Course> Courses { get; set; }
public virtual DbSet<Enrollment> Enrollments { get; set; }
public virtual DbSet<Student> Students { get; set; }
}

Database Name
If you pass the database name as a parameter in a base constructor of the context class,
then Code First will create a database automatically again, but this time the name will be the
one passed as parameter in the base constructor on the local SQLEXPRESS database
server.

public class MyContext : DbContext {


public MyContext() : base("MyContextDB") {}
public virtual DbSet<Course> Courses { get; set; }
public virtual DbSet<Enrollment> Enrollments { get; set; }
public virtual DbSet<Student> Students { get; set; }
}

Connection String Name


You may choose to put a connection string in your app.config file.

 If the name of the connection string matches the name of your context (either
with or without namespace qualification), then it will be found by DbContext
when the parameter less constructor is used.
 If the connection string name is different from the name of your context, then
you can tell DbContext to use this connection in Code First mode by passing
the connection string name to the DbContext constructor.
public class MyContext : DbContext {
public MyContext() : base("name = MyContextDB") {}
public virtual DbSet<Course> Courses { get; set; }
public virtual DbSet<Enrollment> Enrollments { get; set; }
public virtual DbSet<Student> Students { get; set; }
}

 In the above code, snippet of context class connection string is specified as a


parameter in the base constructor.
 Connection string name must start with "name=" otherwise, it will consider it
as a database name.
 This form makes it explicit that you expect the connection string to be found in
your config file. An exception will be thrown if a connection string with the
given name is not found.

<connectionStrings>
<add name = "MyContextDB"
connectionString = "Data Source =.;Initial Catalog = EFMyContextDB;Integrated Security =
true"
providerName = "System.Data.SqlClient"/>
</connectionStrings>

 The database name in the connection string in app.config


is EFMyContextDB. CodeFirst will create a new EFMyContextDB database
or use existing EFMyContextDB database at local SQL Server.

You might also like