Created
February 20, 2015 14:30
-
-
Save ajtowf/5710ef55b29cbff1bcba to your computer and use it in GitHub Desktop.
EntityFramework Change Tracking
This file contains hidden or 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
public class Db : DbContext | |
{ | |
public Db() : base("Db") | |
{ | |
Configuration.LazyLoadingEnabled = true; | |
} | |
public DbSet<Foo> Foos { get; set; } | |
public DbSet<Bar> Bars { get; set; } | |
} |
This file contains hidden or 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
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(); | |
} | |
} |
This file contains hidden or 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
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; } | |
} |
This file contains hidden or 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
[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