Sunday, May 6, 2012

Minimal Code to Demonstrate Entity Framework Code First

Before compiling this, to ensure your project has a reference to a version of Entity Framework that supports code first development, execute the following nuget command:

install-package EntityFramework

The following code listing contains:
  • POCO
  • Context
  • Static method to add an item
  • Application configuration (XML)
  • Unit test (not required)

using System;
using System.Data.Entity;
namespace EFCodeFirst
{
public class Thing
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Model : DbContext
{
public DbSet<Thing> Things { get; set; }
}
public class AddThing
{
public static void Main()
{
var thing = new Thing { Name = @"Something" };
using (var model = new Model())
{
model.Things.Add(thing);
model.SaveChanges();
}
Console.WriteLine("saved changes");
Console.ReadLine();
}
}
}
view raw AddThing.cs hosted with ❤ by GitHub
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework"
type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=4.3.1.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</configSections>
<entityFramework>
<defaultConnectionFactory
type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework">
<parameters>
<parameter
value="Data Source=.\SQLEXPRESS; Integrated Security=True; MultipleActiveResultSets=True" />
</parameters>
</defaultConnectionFactory>
</entityFramework>
</configuration>
view raw App.config hosted with ❤ by GitHub
using System.Data.SqlClient;
namespace EFCodeFirst.Test
{
public class AddThingTest
{
public void MainTest()
{
AddThing.Main();
int? rowCount = null;
using (var connection = new SqlConnection(@"Data Source=.\musicdb; Integrated Security=True;"))
using (var command = new SqlCommand("select count(*) from [EFCodeFirst.Model].dbo.Things", connection))
{
connection.Open();
try
{
rowCount = command.ExecuteScalar() as int?;
}
finally
{
connection.Close();
}
}
Assert.IsNotNull(rowCount);
Assert.IsTrue(rowCount > 0);
}
}
}
view raw Test.cs hosted with ❤ by GitHub

No comments:

Post a Comment