0

同じテーブルに親子関係を持つエンティティ フレームワークのモデルがあります。これは、0,1 対多のマッピングです。現在、多くのプロパティがあります。あるシナリオでは、これらすべてのプロパティが必要ではなく、ID、名前、および子だけが必要です。

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