[英]EF cast to view model tree structure
我在实体框架中有一个模型,在同一张表中有父子关系。 它是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”的对象。
有什么方法可以铸造树结构以查看树模型?
如果定义了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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.