简体   繁体   中英

What is my mistake in implementing Foreign Key with EF 6?

I am currently in the process of learning ASP.NET MVC 5 with EF 6. Right now I am stuck with declaring a foreign key with Fluent API and then seeding data to the declared tables. Here's the code I have:

Models:

public class Person
{
    public int Id { get; set; }
    public ICollection<Anime> DirectedAnimes { get; set; }
}

public class Anime
{
    public int Id { get; set; }
    public int DirectorId { get; set; }
    public Person Director { get; set; }
}


public class AnimeDbContext : DbContext
{
    public DbSet<Person> Persons { get; set; }
    public DbSet<Anime> Animes { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Anime>()
            .HasRequired(a => a.Director)
            .WithMany(p => p.DirectedAnimes)
            .HasForeignKey(p => p.DirectorId);
        base.OnModelCreating(modelBuilder);
    }
}

Seeding data:

public class AnimeInitializer : DropCreateDatabaseAlways<AnimeDbContext>
{
    protected override void Seed(AnimeDbContext context)
    {   
        var persons = new List<Person>
        {
            new Person { Id = 1 },
            new Person { Id = 2 }
        };
        var animes = new List<Anime>
        {
            new Anime { DirectorId = 1 },
            new Anime { DirectorId = 2 }
        };
        persons.ForEach(p => context.Persons.Add(p));
        context.SaveChanges();
        animes.ForEach(a => context.Animes.Add(a));
        context.SaveChanges();
    }
}

But when I fetch Anime objects they have expected DirectorId values, but their Director properties are null :

var director = (new AnimeDbContext()).Animes.First().Director; //null
var directorId = (new AnimeDbContext()).Animes.First().DirectorId; //1

Entity framework knows about the foreign key though, because adding new Anime {DirectorId = 3} in the Seed method results in a runtime error.

I am pretty sure that my mistake is very dumb and is caused by me not following examples precisely, but I've been struggling with this problem for a while already and still can't figure it out. I would very much appreciate some help.

Your navigation-property is not virtual and thus cannot be overridden by the DynamicProxy.

Change it like this:

public class Person
{
    public int Id { get; set; }
    public virtual ICollection<Anime> DirectedAnimes { get; set; }
}

public class Anime
{
    public int Id { get; set; }
    public int DirectorId { get; set; }
    public virtual Person Director { get; set; }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM