简体   繁体   中英

Entity Framework navigation properties is empty after assigned Id

I have the following

public class MainClass {
    public int Id  { get;set; }

    public virtual ICollection<SubClass> SubClasses { get;set; }
}

public class SubClass {
    public int MainClassId  { get;set; }

    public virtual MainClass MainClass { get;set; }
}

and i have setup mapping for one to many. The problem i have is when i do this :

var subClass = new SubClass();
subClass.MainClassId = 1;
_dbset.SaveChanges(subClass);

//subClass.MainClass is null after save

i will need to call my get function with id=1 only i can get the MainClass entity. Anyone has any idea whats the issue causing this?

You should add subClass to the mainClass's collection of SubClasses and then save changes.

So like,

var mainClass = _dbset.MainClasses.Single(x => x.id == mainClassId); 
var subClass = new SubClass();
//populate subClass without setting mainclassId.
mainClass.SubClasses.Add(subClass);
_dbset.SaveChanges();

The following would work:

public class MainClass {
    public int Id  { get;set; }

    public virtual  ICollection<SubClass> SubClasses { get;set; }
}

public class SubClass {
    public int Id  { get;set; }
    [ForeignKey("MainClass")]
    public int MainClassId  { get;set; }

    public virtual MainClass MainClass { get;set; }
}

If you used code-first approach, you might be missing modelbuilder for 1:M relationship. In your Context in method OnModelCreating you need to have something like this.

modelBuilder.Entity<MainClass>()
      .HasMany(e => e.SubClass)
      .WithRequired(e => e.MainClass)
      .WillCascadeOnDelete();

Next thing that comes to my mind is that you might want to use include in your get method to specify that you need to load all subclasses for main class

 context.MainClass.Include(x => x.SubClass).ToList();

or use some other method to load joined data. Link

I hope that will help you.

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