0

我在实体框架中有一个模型,在同一张表中有父子关系。它是一个 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”类型。

有没有办法将树结构投射到树的视图模型?

4

1 回答 1

3

如果您定义了一种,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();
于 2015-09-24T14:45:22.057 回答