Database Reference
In-Depth Information
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public DbSet<Speaker> Speakers { get; set; }
public DbSet<Talk> Talks { get; set; }
public override int SaveChanges()
{
var changeSet = this.ChangeTracker.Entries().Where(e => e.Entity is Talk);
if (changeSet != null)
{
foreach (var entry in changeSet.Where(c => c.State ==
System.Data.Entity.EntityState.Added).Select(a => a.Entity as Talk))
{
entry.CreateDate = DateTime.UtcNow;
entry.RevisedDate = DateTime.UtcNow;
}
foreach (var entry in changeSet.Where(c => c.State ==
System.Data.Entity.EntityState.Modified).Select(a => a.Entity as Talk))
{
entry.RevisedDate = DateTime.UtcNow;
}
}
return base.SaveChanges();
}
}
The following is the output of the code in Listing 8-10:
talk1.Speaker is null: True
talk1.Speaker is null: False
Number of added entries tracked: 2
talk1's state is: Unchanged
talk1's state is: Modified
Speaker: Karen Stanfield
Talk Title: AI with C# in 3 Easy Steps
How It Works
The code in Listing 8-10 is a little involved, so let's take it one step at a time. First off, we create a speaker and a talk.
Then we add the talk to the speaker's collection. At this point, the talk is part of the speaker's collection, but the
speaker is not part of the talk's collection. The other side of the association has not been fixed up just yet.
Next we add the speaker to the DbContext with Add(speaker1) . The second line of the output shows now that
the talk's speaker collection is correct. Entity Framework has fixed up the other side of the association. Here Entity
Framework did two things. It notified the object state manager that there are three entries to be created, although
it is not shown in the result of number of entities added by Entity Framework, as it considers many-to-many
 
Search WWH ::




Custom Search