EF转换为查看模型树结构

时间:2015-09-24 14:24:13

标签: c# entity-framework viewmodel self-referencing-table

我在实体框架中有一个模型,在同一个表中有父子关系。这是一个0.1到多的映射。现在它有很多属性,在一种情况下我不想要所有这些属性,只有Id,Name和Children。

public partial class Foo
{
    public Foo()
    {
        this.As = new HashSet<A>();
        this.Children = new HashSet<Foo>();
        this.Bs = new HashSet<B>();
    }

    public int FooId { get; set; }
    public Nullable<int> ParentId { get; set; }
    public string ParentName { get; set; }
    public string Name { get; set; }
    //... many more

    public virtual ICollection<A> As { get; set; }
    public virtual ICollection<Foo> Children { get; set; }
    public virtual Foo Foo2 { get; set; }
    public virtual ICollection<B> Bs { get; set; }
}

我希望将这些列表转换为

public class FooModel
{
    public FooModel()
    {
        this.Children = new HashSet<FooModel>();
    }

    public int FooId { get; set; }
    public Nullable<int> ParentId { get; set; }
    public string Name { get; set; }

    public virtual ICollection<FooModel> Children { get; set; }
    public virtual FooModel Foo2 { get; set; }
}

我正在做如下。

db.Foos.Where(p => p.ParentId == null).Cast<FooModel>().ToList();

并收到错误

  

无法投射类型的对象   输入'System.Data.Entity.DynamicProxies.Foo_ALongNoInHexadecimal'   'Namespace.ViewModel.FooModel'。

有没有办法转换树结构来查看树的模型?

1 个答案:

答案 0 :(得分:4)

Cast<>扩展方法不会应用用户定义的转换(如果已定义)。它只能转换为接口或所提供类型的类层次。

尝试定义一个接受你模型的构造函数,例如

public class FooModel
{
    public FooModel(Foo myFoo)
    {
        this.Children = new HashSet<FooModel>();
        if(myFoo != null)
        {
            FooId = myFoo.FooId;
            ParentId = myFoo.ParentId;
            Name = myFoo.Name;
            //Foo2 = new FooModel(myFoo.Foo2);
            Childern = myFoo.Children.Select(c=> new FooModel(c));
        }
    }

    public int FooId { get; set; }
    public Nullable<int> ParentId { get; set; }
    public string Name { get; set; }

    public virtual ICollection<FooModel> Children { get; set; }
    public virtual FooModel Foo2 { get; set; }
}

使用它:

db.Foos.Where(p => p.ParentId == null).Select(c => new FooModel(c)).ToList();