Ng Chee Fi
Ng Chee Fi

Reputation: 55

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?

Upvotes: 1

Views: 235

Answers (3)

Topher
Topher

Reputation: 1029

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();

Upvotes: 1

Kamil Folwarczny
Kamil Folwarczny

Reputation: 591

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.

Upvotes: 0

el_M
el_M

Reputation: 159

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; }
}

Upvotes: 0

Related Questions