Entity Framework, Code First, Update "one to many" relationship with independent associations

Martin picture Martin · Aug 7, 2011 · Viewed 14.8k times · Source

It took me way too long to find a solution to the scenario described below. What should seemingly be a simple affair proved to be rather difficult. The question is:

Using Entity Framework 4.1 (Code First approach) and "Independent associations" how do I assign a different end to an existing "many to one" relationship in a "detached" scenario ( Asp.Net in my case).

The model:

I realize that using ForeignKey relationships instead of Independent Associations would have been an option, but it was my preference to not have a ForeignKey implementation in my Pocos.

A Customer has one or more Targets:

    public class Customer:Person
{
    public string Number { get; set; }
    public string NameContactPerson { get; set; }
    private ICollection<Target> _targets;

    // Independent Association
    public virtual ICollection<Target> Targets
    {
        get { return _targets ?? (_targets = new Collection<Target>()); }
        set { _targets = value; }
    }
}

A Target has one Customer:

    public class Target:EntityBase
{
    public string Name { get; set; }
    public string Description { get; set; }
    public string Note { get; set; }
    public virtual Address Address { get; set; }
    public virtual Customer Customer { get; set; }
}

Customer derives from a Person class:

    public class Person:EntityBase
{        
    public string Salutation { get; set; }
    public string Title { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set  ; }        
    public string Telephone1 { get; set; }
    public string Telephone2 { get; set; }
    public string Email { get; set; }        

    public virtual Address Address { get; set; }
}

EntityBase class provides some common properties:

    public abstract class EntityBase : INotifyPropertyChanged
{
    public EntityBase()
    {
        CreateDate = DateTime.Now;
        ChangeDate = CreateDate;
        CreateUser = HttpContext.Current.User.Identity.Name;
        ChangeUser = CreateUser;
        PropertyChanged += EntityBase_PropertyChanged;
    }

    public void EntityBase_PropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        if (Id != new Guid())
        {
            ChangeDate = DateTime.Now;
            ChangeUser = HttpContext.Current.User.Identity.Name;
        }
    }

    protected virtual void OnPropertyChanged(PropertyChangedEventArgs e)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null) handler(this, e);
    }

    public event PropertyChangedEventHandler PropertyChanged;

    public Guid Id { get; set; }
    public DateTime CreateDate { get; set; }
    public DateTime? ChangeDate { get; set; }
    public string CreateUser { get; set; }
    public string ChangeUser { get; set; }
}

The Context:

    public class TgrDbContext : DbContext
{
    public DbSet<Person> Persons { get; set; }
    public DbSet<Address> Addresses { get; set; }
    public DbSet<Customer> Customers { get; set; }
    public DbSet<Target> Targets { get; set; }
    public DbSet<ReportRequest> ReportRequests { get; set; }

    // If OnModelCreating becomes to big, use "Model Configuration Classes"
    //(derived from EntityTypeConfiguration) instead
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Person>().HasOptional(e => e.Address);            
        modelBuilder.Entity<Customer>().HasMany(c => c.Targets).WithRequired(t => t.Customer);            
    }

    public static ObjectContext TgrObjectContext(TgrDbContext tgrDbContext)
    {           
        return ((IObjectContextAdapter)tgrDbContext).ObjectContext;
    }
}

Answer

Ladislav Mrnka picture Ladislav Mrnka · Aug 7, 2011

I waited for @Martin answer because there are more solutions for this problem. Here is another one (at least it works with ObjectContext API so it should work with DbContext API as well):

// Existing customer
var customer = new Customer() { Id = customerId };
// Another existing customer
var customer2 = new Customer() { Id = customerId2 };

var target = new Target { ID = oldTargetId };
// Make connection between target and old customer
target.Customer = customer;

// Attach target with old customer
context.Targets.Attach(target);
// Attach second customer
context.Customers.Attach(customer2);
// Set customer to a new value on attached object (it will delete old relation and add new one)
target.Customer = customer2;

// Change target's state to Modified
context.Entry(target).State = EntityState.Modified;
context.SaveChanges();

The problem here is internal state model and state validations inside EF. Entity in unchanged or modified state with mandatory relation (on many side) cannot have independent association in added state when there is no other in deleted state. Modified state for association is not allowed at all.