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.
- Am I missing anything here? Even though I kept "virtual" for every property, the object is not being tracked. Why?
- Do I have to write "Association fixup" logic as was done in EF4 POCOs?
- If so, why was the Association fixup code removed in DbContext T4 generator?