I am having some trouble removing an optional one-to-one navigation property.
In my scenario, a person has a single address. This address is optional.
After reading http://blog.bennymichielsen.be/2011/06/02/entity-framework-4-1-one-to-one-mapping/ I have modeled my domain this way:
public class Person
{
public Guid Id { get; set; }
public string Name { get; set; }
public virtual Address Address { get; set; }
}
public class Address
{
public Guid Id { get; set; }
public string Street { get; set; }
[Required]
public virtual Person Person { get; set; }
}
public class PersonContext : DbContext
{
public DbSet<Person> People { get; set; }
}
The problem occurs when I try to remove the address from a person. The following code will fail
using (PersonContext context = new PersonContext())
{
Person person = context.People.Find(personId);
person.Address = null;
context.SaveChanges();
if (person.Address == null)
{
Console.WriteLine("Success: Person.Address is null.");
}
else
{
Console.WriteLine("Failure: Person.Address is not null.");
}
}
Both Person and Address are proxies. This will work if the address is loaded into the context somehow (eager or lazy loading).
Any help will be greatly appreciated.
Thank you