实体框架未加载相关对象 [英] Entity Framework not loading related objects

查看:82
本文介绍了实体框架未加载相关对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Entity Framework的新手,但是可能会误解某些事情,或者做错了什么事情。

I am new to Entity Framework, but might be misunderstanding something, or doing something wrong.

我的代码,是给我一个特定人员的任务列表:

My code, to get me a list of tasks for a particular person :

 public List<TaskObject> GetAssignedTasks(int personId)
        {
            var items = (from s in _te.tasks where s.person.person_id == personId select s).ToList();
            var tasks = new List<TaskObject>();
            foreach (var t in items)
            {

                TaskObject tk = Transformer.UnpackTask(t);

                tasks.Add(tk);
            }
            return tasks;
        }

我的问题是,似乎返回了记录列表,但相关项目未加载。我的 Transformer.UnpackTask方法采用我加载的任务实体,然后将其转换为通过业务/服务层到达UI的其他对象。

My problem is, it seems to get a list of records back, but related items are not loaded. My 'Transformer.UnpackTask' method takes the task entity which I loaded, and then transforms it into a different object which goes up to the UI via the business/service layers.

但是,一旦我的Unpacker函数尝试引用作为相关对象的项目(例如,任务具有一个 AssignedPerson,该对象具有一个包含人员详细信息的Person实体。但是我的实体的AssignedPerson属性为NULL。

But as soon as my Unpacker function tries to references an item which is a related object (For example, a task has an 'AssignedPerson', which has a Person entity with person details. But the AssignedPerson property of my entity is NULL. I thought it would load the related items.

我误会了吗?

推荐答案

您应该使用Include()方法显式地包含引用。
它有两个重载:一个将属性作为lambda表达式,另一个将路径作为字符串加载(在需要加载引用时有用)集合中可用的对象)。

You should explicitly include references with the Include() method. It has two overloads: one takes the property as lambda expression, the other takes the path to load as a string (useful when you need to load references on objects available in collections).

MSDN参考

这篇关于实体框架未加载相关对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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