EF转换以查看模型树结构

EF cast to view model tree structure

我在 entity framework 中有一个模型,在同一个 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();

出现错误

Unable to cast object of type 'System.Data.Entity.DynamicProxies.Foo_ALongNoInHexadecimal' to type 'Namespace.ViewModel.FooModel'.

有什么方法可以转换树结构来查看树模型吗?

Cast<> 扩展方法不应用用户定义的转换,如果您已定义的话。它只能转换为接口或在所提供类型的 class 层次结构中。

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

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();