EF 5.0不删除可选的一对一导航属性

时间:2013-01-30 22:30:36

标签: entity-framework lazy-loading code-first

在Entity Framework 5中将可选的一对一导航属性设置为null似乎无法进入数据库。这是预期的行为吗?

在下面的示例中,Person是一个代理对象。我希望将地址设置为null将导致地址从数据库中删除。

如果我在设置为null之前懒惰加载地址,则下面的代码有效。但是在

之前加载地址

非常感谢任何帮助。

namespace ConsoleApplication2
{
using System;
using System.Data.Entity;

internal class Program
{
    private static void Main(string[] args)
    {
        using (PersonContext context = new PersonContext())
        {
            // Make sure person with Id = 1 exists with an address.
            Person person = context.People.Find(1) ?? context.People.Add(new Person { Id = 1 });
            if (person.Address == null)
            {
                person.Address = new Address
                    {
                        Street = "123 Main Street",
                        City = "SomeCity",
                        State = new State
                        {
                            Code = "NY",
                            Name = "New York"
                        },
                        Zip = "11771"
                    };
            }
            context.SaveChanges();
        }

        // Setting address to null should remove relationship 
        using (PersonContext context = new PersonContext())
        {
            Person person = context.People.Find(1);

            Console.WriteLine("Person is a " + person.GetType());

            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.");
            }
        }
    }
}

public class Person
{
    public int Id { get; set; }
    public virtual Address Address { get; set; }
}

public class Address
{
    public int Person_Id { get; set; }
    public string Street { get; set; }
    public string City { get; set; }
    public int StateId { get; set; }
    public State State { get; set; }
    public string Zip { get; set; }
}

public class State
{
    public int Id { get; set; }
    public string Code { get; set; }
    public string Name { get; set; }
}

public class PersonContext : DbContext
{
    public DbSet<Person> People { get; set; }

    public DbSet<State> States { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Entity<Address>()
            .HasKey(x => x.Person_Id);

        modelBuilder.Entity<Person>()
            .HasOptional<Address>(x => x.Address)
            .WithRequired()
            .WillCascadeOnDelete();
    }
}

}

1 个答案:

答案 0 :(得分:0)

如果您没有使用延迟加载,则不会加载相关属性(如Address),因此已经为null。

要确保始终加载,请使用预先加载:

Person person = context.People.Include(x => x.Address).Single(x => x.Id == 1);