Skip to content

Instantly share code, notes, and snippets.

@ajtowf
Created February 20, 2015 14:30
Show Gist options
  • Save ajtowf/5710ef55b29cbff1bcba to your computer and use it in GitHub Desktop.
Save ajtowf/5710ef55b29cbff1bcba to your computer and use it in GitHub Desktop.
EntityFramework Change Tracking
public class Db : DbContext
{
public Db() : base("Db")
{
Configuration.LazyLoadingEnabled = true;
}
public DbSet<Foo> Foos { get; set; }
public DbSet<Bar> Bars { get; set; }
}
public class DbInitializer : DropCreateDatabaseAlways<Db>
{
protected override void Seed(Db context)
{
context.Foos.Add(new Foo
{
Value = "Value",
Bars = new List<Bar>
{
new Bar { Value = "Value" }
}
});
context.SaveChanges();
}
}
public class Foo
{
public int Id { get; set; }
public string Value { get; set; }
public virtual ICollection<Bar> Bars { get; set; }
}
public class Bar
{
public int Id { get; set; }
public string Value { get; set; }
public int FooId { get; set; }
public virtual Foo Foo { get; set; }
}
[TestFixture]
public class Test
{
[Test]
public void TestChangeTracking()
{
System.Data.Entity.Database.SetInitializer(new DbInitializer());
Foo foo;
// Read and send to the client over the wire
using (var db = new Db())
{
foo = db.Foos.First();
Assert.AreEqual(1, foo.Bars.Count);
}
// Client changes some values
foo.Value = "Changed";
foo.Bars.First().Value = "Changed";
// Post to server for an update
using (var db = new Db())
{
db.Foos.AddOrUpdate(foo);
db.SaveChanges();
}
// What got saved?
using (var db = new Db())
{
foo = db.Foos.First();
Console.WriteLine("Foo.Value: {0}", foo.Value);
Console.WriteLine("Foo.Bars[0].Value: {0}", foo.Bars.First().Value);
}
Assert.Fail("Use nhibernate instead.");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment