Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I have two models and first model has a property ICollection. I have one to many

ID: 3851680 • Letter: I

Question

I have two models and first model has a property ICollection. I have one to many relationship between them and I defined that using fluent API (using entity framework). But in SQL server I am only seeing first model's table populate with data. The second model's table does not populate as I insert data. Here is more details:

Model 1:

public class Model1{

public int? PersonId { get; set; }
public string LastName { get; set; }
public string FirstName { get; set; }

  public virtual ICollection model2 { get; set; }

}

Model 2:

public class Model2{

public int? Id { get; set; }
public int PersonId { get; set; }
public int number { get; set; }

}

Fulent API:

modelBuilder.Entity<Model1>().HasMany(x => x.model2).WithRequired();

I have a feeling I am supposed to put something inside WithRequired()?

why is the table for not populating?

Explanation / Answer

Hi,

Yes, you are right, the definition of one to many relationship is that Model 1 can have multiple model 2 rows related but each model 2 rows should be related to atleast one row of model 1. so, you can write the above like,

or, you can use,

modelBuilder.Entity<Model1>() .HasMany(u => u.model2) .

WithRequired() .HasForeignKey(h => h.PersonId );

additionally you can try and include HasForeignKey if you have it defined in the above structure.

Thumbs up if this was helpful, otherwise let me know in comments. Good day.