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 using the Designer (or the XML mapping files) later to further optimize the model. The priority is the database – the code and the model are only secondary. When your priority is the code and you want to begin from scratch without any existing schema or XML mapping files using source code, then the approach is called CodeFirst. Code-First enables an easy development workflow. It enables you to:
- Develop without opening the designer or mapping in XML files.
- Define model objects by simply writing POCO(Plain old CLR object) with no base classes required
- Use a “convention over configuration” approach that enables database persistence without explicitly configuring anything
You can download the latest version of code first from this url : ADO.NET Entity Framework 4.1 – Update 1.
You can also install via NuGet.
install-package entityframework
Quick CRUD example with EF Code first.
First we will create the model classes.
public class Task
{
public int TaskId { get; set; }
public string TaskDescription { get; set; }
public DateTime TaskDate { get; set; }
public short TaskPriority { get; set; }
public bool TaskIsDone { get; set; }
}
Now we need to create a Context for this. Context is required to use the POCO classes for DataAccess. It can be implemented by deriving it from DbContext class. The DbContext class is available under System.Data.Entity namespace.
public class TaskContext : DbContext
{
public DbSet Tasks { get; set; }
}
We are done.
Now we can use this class for communicating to Database.
Inserting records to Database.
using (TaskContext taskContext = new TaskContext())
{
taskContext.Tasks.Add(new Task()
{
TaskDate = DateTime.Today,
TaskDescription = "Create a blog post",
TaskIsDone = false,
TaskPriority = 1
});
if (taskContext.SaveChanges() != 0)
{
Console.WriteLine("Task added.");
}
}
Updating records, updating the first task from Tasks, if the Task date is today.
using (TaskContext taskContext = new TaskContext())
{
var currentTask = taskContext.Tasks.Where
(task => task.TaskDate == DateTime.Today).FirstOrDefault();
currentTask.TaskIsDone = true;
if (taskContext.SaveChanges() != 0)
{
Console.WriteLine("Task updated.");
}
}
Removing records, removing first task from Tasks, if the Task is completed.
using (TaskContext taskContext = new TaskContext())
{
var completedTask = taskContext.Tasks.Where
(task => task.TaskIsDone == true).FirstOrDefault();
taskContext.Tasks.Attach(completedTask);
taskContext.Tasks.Remove(completedTask);
if (taskContext.SaveChanges() != 0)
{
Console.WriteLine("Task Deleted.");
}
}
And retriving records, retriving all the tasks.
using (TaskContext taskContext = new TaskContext())
{
var tasks = taskContext.Tasks.Where
(task => task.TaskDate == DateTime.Today);
tasks.ToList().ForEach(task =>
Console.WriteLine("Task : {0} IsCompleted : {1}",
task.TaskDescription, task.TaskIsDone));
}
It is very easy right? Another interesting question is where this data is getting stored? Because we didn’t specified any Database, or Connection string. By default the database will be created on local instance of SQLEXPRESS (localhost\SqlExpress). The database is named after the fully qualified name of your derived context, in our case that it will be “EFCodeFirst.TaskContext”. You can control this by providing connection string or by setting DefaultConnectionFactory.
You can provide connectionstring either in App.Config / Web.Config file or in code.
If you are providing the connection string in config, file the name of the connection string element should be same as Context class name. Like this
<connectionStrings>
<add name="TaskContext"
connectionString="Server=.\SqlExpress; Integrated Security=SSPI; Database=TaskDb;"
providerName="System.Data.SqlClient"/>
</connectionStrings>
And if you want to use your own connection string name, you can do this using CreateConnection() method of the DefaultConnectionFactory class. You can also specify the connection string. You need to provide this information before creating the instance of task context.
Database.DefaultConnectionFactory.CreateConnection("TaskDbConnection");
using (TaskContext taskContext = new TaskContext())
{
//Code.
}
Entity Framework also supports various databases also, like SQL CE, MySql etc. This can be achive either using the provider name is the config settings or by using DefaultConnectionFactory propery of Database class. Following statement helps to use SqlCe database instead of Sql Server
Database.DefaultConnectionFactory =
new SqlCeConnectionFactory("System.Data.SqlServerCe.4.0");
using (TaskContext taskContext = new TaskContext())
{
//Code.
}
Model validations also supported by entity framework. I may cover them in another post.
Happy 2012