问题
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; }
}
回答1:
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
回答2:
Include can do it. As you use generic repository after I read your comments, you can replace your generic Get() function with this.
var list = db.Set<T>();
var key = db.Model.FindEntityType(typeof(T)).FindPrimaryKey().Properties.FirstOrDefault();
var foreignkeys = key.GetContainingPrimaryKey().GetReferencingForeignKeys();
if (foreignkeys.Count() > 0)
{
foreach (var item in foreignkeys)
list = list.Include<T>(item.DeclaringEntityType.DisplayName());
}
return list;
回答3:
Try to use below code in your repository to include navigation properties for your _context.Set<T>:
var query = _context.Set<T>().AsQueryable();
foreach (var property in _context.Model.FindEntityType(typeof(T)).GetNavigations())
query = query.Include(property.Name);
return await query.ToListAsync();
Refer to Include all navigation properties using Reflection in generic repository using EF Core
回答4:
It is about the ORM (Object-relational mapping) pattern you use.
This patterns are the ways how you want to load related entities; eager, load, ...
You can reach related entity by (most common way) Include() or you can choose any other pattern according to your project. Please take a look at here
来源:https://stackoverflow.com/questions/59852751/list-returned-by-entity-framework-is-null