Created
May 6, 2012 22:08
-
-
Save gabrielgreen/2624784 to your computer and use it in GitHub Desktop.
entity framework code first quick start
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment