实体框架返回的列表为null [英] List returned by Entity Framework is null

查看:98
本文介绍了实体框架返回的列表为null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个类,具有一对多关系的 Field Field2

I have these two classes, Field and Field2 with a one-to-many relationship.

当我尝试获取 Field 时,列表返回带有ID和名称的记录,这是正确的。但是尝试从 Field 读取 Field2 总是空的。

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.

可能是什么原因?我已经尝试了一切。我可以在数据库中看到FK等。

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; }
}


推荐答案

Include可以做到。当我在阅读注释后使用通用存储库时,可以用此替换通用Get()函数。

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;

这篇关于实体框架返回的列表为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆