I am trying to reproduce the same behavior as EntityObject using CTP5 DBContext for change tracking. Consider the tables Movie and Director. Relationship is only 1 director for a movie and multiple movies for each director.
var movie = new Movie();
movie.Name = "ABCD";
ctx.Movies.Add(movie);//ctx.Movies.AddObject(movie);
movie.Director = new Director() { Name = "dir1" };
var existingDirector = ctx.Directors.Where(a => a.Name == "dir2").FirstOrDefault();
movie.Director = existingDirector;
ctx.SaveChanges();
If I run this using EntityObject, this code would create a new director "dir1" as the changes are tracked. If I run this code using CTP 5 DbContext generator, the new director "dir1" is not created. I changed the properties to be virtual in both Movie and Director objects. Below is the code.
public partial class Director
{
public Director()
{
//this.Movies = new HashSet<Movie>();
}
// Primitive properties
public virtual int DirectorId { get; set; }
public virtual string Name { get; set; }
// Navigation properties
public virtual ICollection<Movie> Movies { get; set; }
}
public partial class Movie
{
public Movie()
{
//this.Actors = new HashSet<Actor>();
}
// Primitive properties
public virtual int MovieId { get; set; }
public virtual Nullable<int> DirectorId { get; set; }
public virtual string Name { get; set; }
// Navigation properties
public virtual Director Director { get; set; }
}
I have 3 questions.
Of course the new director does not get saved because you changed the new movie's director to an existing one at some later point in your code, try this one and you'll get them both saved into DB:
var movie = new Movie();
movie.Name = "ABCD";
ctx.Movies.Add(movie);
movie.Director = new Director() { Name = "dir1" };
//movie.Director = existingDirector;
ctx.SaveChanges();
You can write your own Association fixup logic but that's going to take care of keeping the endpoints of your associations in sync, and has nothing to do with the code you showed here.
The reason that your code saves the new director into the DB when using EntityObjects is because of a concept that called Relationship Span. The relationship span defines that the ObjectContext will automatically attach an entity when you have joined it to another attached entity. If that detached object is new, when it is attached to the context its EntityState will be Added. However this Relationship Span behavior is not implemented even when you are using POCO proxies (i.e. making your navigation properties virtual).