Entity Framework not loading related objects

后端 未结 3 1479
醉酒成梦
醉酒成梦 2021-01-05 15:07

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 :

3条回答
  •  时光取名叫无心
    2021-01-05 15:52

    try this. What we are trying to do here is include the related entity in the select query itself, lazy load. So when you are unpacking the task you should be able to get the related entity aswell.

    Things to check:

    • The task entity should have the browse ability to the person entity else this will fail.
    • Add the [Include] keyword on top of the person entities inside the metadata of task in the metadata file in your service layer.

    -- E.g. metadata file of the service you created.

    tasks metadata
     {
     ... 
     ... 
    
      \\these two should already be there you will just have to add the Include and
      \\ Key attribute.
    
        [Include]
        public EntityCollection Person {get; set;}
        [Key]  \\ that connects the task and person entity (FK/PK)
        public int PersonID {get;set;}
    }
    

    the service file

    public List GetAssignedTasks(int personId)
        {
            var items = (from s in _te.tasks.Include("Person") where s.person.person_id == personId select s).ToList();
            var tasks = new List();
            foreach (var t in items)
            {
    
                TaskObject tk = Transformer.UnpackTask(t);
    
                tasks.Add(tk);
            }
            return tasks;
        }
    

    Hope it helps. Cheers

提交回复
热议问题