0

I have a model in entity framework with parent child relationship in same table. It is a 0,1 to many mapping. Now it have many properties, at one scenario I don't want all these properties, just Id, Name and 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; }
}

I want the list of these to converted to

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; }
}

I am doing as below.

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

and getting error

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

Is there any way to cast a tree structure to view model of tree?

Oluwafemi
  • 14,243
  • 11
  • 43
  • 59
Chaitanya Gadkari
  • 2,669
  • 4
  • 30
  • 54

1 Answers1

3

The Cast<> extension method does not apply user-defined conversions, if you have one defined. It can only cast to interfaces or within the class heirarchy of the supplied type.

try defining a constructor that accepts you model e.g.

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; }
}

use it:

db.Foos.Where(p => p.ParentId == null).Select(c => new FooModel(c)).ToList();
Chaitanya Gadkari
  • 2,669
  • 4
  • 30
  • 54
Overmachine
  • 1,723
  • 3
  • 15
  • 27