monstertjie_za
monstertjie_za

Reputation: 7803

Lazy loading not working with 1 to 0 or 1 relationship

I have the following table design.

enter image description here As can be seen here, there is a one to many relationship, with the many on the EpisodePatient side.

Then, I have the following classes.

public class EpisodeModel
{
    public int ID { get; set; }
    public virtual EpisodePatientModel EpisodePatient { get; set; }
}
public class EpisodePatientModel
{
    public int EpisodePatientID { get; set; }
    public virtual EpisodeModel Episode { get; set; }
}

I am setting up the relationship, in Entity Framework, to be a one to 0 or many. The reason for this is, I am selecting all EpisodePatients from a View, and I want the Episode to be Lazy loaded when accessed.

This is how I am setting up my relationship.

modelBuilder.Entity<EpisodePatientModel>().HasRequired(r => r.Episode).WithOptional(o => o.EpisodePatient);

I want this to act as a One to zero or many in my code, as an Episode will always have an EpisodePatient, and vice versa.

The problem I am facing is, when I load the EpisodePatient, and try to access the Episode linked item, it is always null, and Lazy loading does not occur.

What am I doing wrong here?

UPDATE

This is how I load the original EpisodePatient items.

this.DbContext.EpisodePatients.AsNoTracking();

Upvotes: 0

Views: 374

Answers (2)

LazZiya
LazZiya

Reputation: 5719

I re-created your model but with data annotations like below and it workes fine:

public class EpisodeModel
{
    [Key]
    public int Id { get; set; }
    public string Title { get; set; }

    public virtual EpisodePatientModel EpisodePatient { get; set; }
}

public class EpisodePatientModel
{
    public string Name { get; set; }

    [Key, ForeignKey("Episode")]
    public int EpisodeId { get; set; }
    public virtual EpisodeModel Episode { get; set; }
}

Upvotes: 1

M. Wiśnicki
M. Wiśnicki

Reputation: 6203

Try without AsNoTracking(), because if you use it your context is not tracking and you can't include more data if you need.

And try change to relation one to many.

modelBuilder.Entity<EpisodePatientModel>().HasRequired<Episode>(s => s.Episode).WithMany(s => s.EpisodePatient); 

Upvotes: 0

Related Questions