[英]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.