I have these two classes, Field and Field2 with a one-to-many relationship.
When I am trying to get Field, the list returns with records with the id and the name, which is correct. But trying to read the Field2 from Field is always empty.
What can be the cause? I have tried everything. I can see the FK in the database etc.
public class Field : IEntityBase
{
public int Id { get; set; }
public string Name { get; set; }
[InverseProperty("Field")]
public virtual ICollection<Field2> Field2 { get; set; }
}
public class Field2: IEntityBase
{
public int Id { get; set; }
public int FieldId { get; set; }
[ForeignKey(nameof(FieldId))]
public virtual Field Field { get; set; }
}
You need to use the Include() method. See the example below,
using (var context = new MyContext())
{
var list = context.Field
.Include(f => f.Field2)
.ToList();
foreach (var field in list)
{
Console.WriteLine("Field Name: {0}", field.Name);
foreach (var field2 in field.Field2)
{
Console.WriteLine("\tField 2 ID: {0}", field.Id);
}
}
}
Entity framework Include
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With