Removing one to one optional relationships RRS feed

  • Question

  • 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; }
            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;
                    if (person.Address == null)
                        Console.WriteLine("Success: Person.Address is null.");
                        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

    • Edited by HiJinx1 Friday, February 1, 2013 3:32 PM Clarification
    Friday, February 1, 2013 3:27 PM


  • Hi Hijinx1,

    Welcome to the MSDN forum.

    If you turn off lazy loading, the navigation property will be null except you use eager loading or explicit loading. Thus, if you want to delete the one to one relationship, you are required to load the navigation property first.

    Good day.

    Alexander Sun [MSFT]
    MSDN Community Support | Feedback to us
    Develop and promote your apps in Windows Store
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    • Marked as answer by Alexander Sun Tuesday, February 26, 2013 6:42 AM
    Monday, February 4, 2013 5:13 AM