Let’s create first simple code first example.
Create the Class Library project in Visual Studio 2010. Write two simple Student and Standard entity classes as below (You can use Entity Framework 4.1/4.3/5.0 for this example.):
public class Student { public Student() { } public int StudentID { get; set; } public string StudentName { get; set; } }
Standard Class:
public class Standard { public Standard() { } public int StandardId { get; set; } public string StandardName { get; set; } public string Description { get; set; } }
Now, create context class which is derived from DBContext class with two DbSet properties, one for Student and one for Standard.
namespace SchoolDataLayer { public class Context: DbContext { public Context(): base() { } public DbSet<Student> Students { get; set; } public DbSet<Standard> Standards { get; set; } } }
Now, create console project to test these classes as below:
using (var ctx = new Context()) { Student stud = new Student() { StudentName = "New Student" }; ctx.Students.Add(stud); ctx.SaveChanges(); }
Now, if you run the application then you will surprise to see that application run successfully.
It has successfully stored Student information into the database. But where is database and what are the tables and its columns??
This is the beauty of Code First APIs of Entity Framework. It creates the database based on parameter passed in the base constructor of your context class. We have not passed any parameters so it will create “SchoolDataLayer.Context” database in local SQLEXPRESS. We will see database initialization workflow in the next chapter.
Code-first API will also create two tables in the database, Students and Standards table based on Student and Standard class. Code First APIs creates PrimaryKey in the table if class has either “Id” or ClassName + “Id” property. For example, Student class has “StudentId” property so it will create StudentId as PK column. It will also create other columns with the same name and datatype as property names and datatype as below.
So this way without creating database first, you can start writing application that will eventually create the database from your domain classes.
Download sample project:
No comments:
Post a Comment