Howsen
Howsen

Reputation: 111

EF returns null for Navagation property

I have two entity models "Course" and "Item" as you can see:

public class Course
{
  public int Id { get; set; }
  public string Name { get; set; }
  public string Description { get; set; }
  public ICollection<CategoryToCourse> Categories { get; set; }
  public ICollection<AuthorToCourse> Authors { get; set; }
  public Item Item { get; set; }

}

And:

public class Item
{
  public int Id { get; set; }
  public decimal Price { get; set; }
  public Course Course { get; set; }
}

But here the 'item' variable is null.

var course = _context.Courses
            .Include(p => p.Item)
            .SingleOrDefault(c => c.Id == 2);
            if (course != null)
            {
              var item = course.Item;
            }

I was unable to spot the problem. Here is database config (maybe it's helpful):

modelBuilder.Entity<Item>(i =>
{
  i.Property(w => w.Price).HasColumnType("Money");
  i.HasKey(w => w.Id);
});

modelBuilder.Entity<Course>(p =>
{
  p.HasKey(w => w.Id);
  p.HasOne<Item>(w => w.Item)
    .WithOne(w => w.Course)
    .HasForeignKey<Item>(w => w.Id);
});

Upvotes: 1

Views: 69

Answers (1)

Michael Wang
Michael Wang

Reputation: 4022

From the above configuration of ModelBuilder, we can see you used Item.Id wrongly as the ForeignKey to bind the Course.
You should set public int CourseRef { get; set; } as the ForeignKey like codes below.

Configuring One To One Relationships In Entity Framework Core

public class Course
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public ICollection<CategoryToCourse> Categories { get; set; }
    public ICollection<AuthorToCourse> Authors { get; set; }
    public Item Item { get; set; }
}
public class Item 
{
    public int Id { get; set; }
    public decimal Price { get; set; }
    public int CourseRef { get; set; }
    public Course Course { get; set; }
}


modelBuilder.Entity<Course>()
    .HasOne(a => a.Item)
    .WithOne(b => b.Course)
    .HasForeignKey<Item>(i => i.CourseRef);

Upvotes: 2

Related Questions