List returned by Entity Framework is null [duplicate]

試著忘記壹切 提交于 2020-02-24 10:15:15

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!