EF Linq投影嵌套馆藏 - 建立关系

时间:2013-03-11 14:41:05

标签: entity-framework linq-to-entities entity-framework-5

我有一个两级嵌套子集合,我将其投影到DTO中。我的问题也适用于普通家长 - >儿童关系:

// There are two types on Parent and two types of Child classes,
// one is EF model, and another is DTO (here I show only one, for simplicity)
public class Parent
{
    public int Id {get;set;}
    public IEnumerable<Child> Children {get;set;}
}

public class Child
{
    public int Id {get;set;}
    public Parent Parent {get;set;}
}

var list = context.Set<Parent>().Select(p=> new DTO.Parent
    {
        Id = p.Id
        Children = (p.Children.Select(c=> new DTO.Child
            {
                Id=c.Id,
                Parent = ?
            }))
    });

在进行投影时是否可以为子对象分配父引用?

2 个答案:

答案 0 :(得分:1)

你可以通过eagar-loading children与Automapper进行映射:

Mapper.CreateMap<Parent, DTO.Parent>();
Mapper.CreateMap<Child, DTO.Child>();
var list = Mapper.Map<IEnumerable<DTO.Parent>>(context.Set<Parrent>()
                                                      .Include(p => p.Children)
                                                      .AsEnumerable());

Automapper会将每个实体映射到dto,并为每个dto子提供对dto父实例的引用。

答案 1 :(得分:0)

我认为不可能直接在查询中设置Parent。所以,这里只是另一种解决方法,类似于“DTO关系修正”:

public class Parent
{
    public int Id {get;set;}

    private IEnumerable<Child> _children;
    public IEnumerable<Child> Children
    {
        get { return _children; }
        set
        {
            _children = value;
            if (_children != null)
                foreach (var child in _children)
                    child.Parent = this;
        }
    }
}