C# 铸造到列表<;T>;Linq to实体查询中的子类型
考虑三类:C# 铸造到列表<;T>;Linq to实体查询中的子类型,c#,linq-to-entities,C#,Linq To Entities,考虑三类: public class MyChildDto { public int Id {get; set;} public string Name {get; set;} } public class MyChildDtos : List<MyChildDto> { public MyChildDtos(List<MyChildDto> myChildDtos) : base(myChildDtos) { }
public class MyChildDto
{
public int Id {get; set;}
public string Name {get; set;}
}
public class MyChildDtos : List<MyChildDto>
{
public MyChildDtos(List<MyChildDto> myChildDtos)
: base(myChildDtos)
{
}
}
public class MyParentDto
{
public int Id {get; set;}
public MyChildDtos Children {get; set;}
}
(为了便于讨论,假设需要MyChildTos类;我只是给出一个简化的示例。)
我遇到的问题是将MyChildEntities
Select的结果转换为适当的类型。使用上面的代码,我收到一个错误,该类型无法隐式转换(从List
到mychildtos
),但存在显式转换。但是,当我尝试显式转换时,我收到一个错误,“LINQ to Entities仅支持强制转换EDM基元或枚举类型”。类似地,如果我尝试显式构造mychildtos
列表(即,将Select结果传递到ctor),我将收到一个错误,Linq to Entities仅支持在查询中使用默认构造函数
是否有某种方法可以从Linq to Entities查询中将
列表
结果转换为MyChildTos
(列表
子类型)?您首先不应该使用MyChildTos
类型。它在这里没有增加任何价值。父类型应简单地键入子类
,作为列表
:
public class MyParentDto
{
public int Id {get; set;}
public List<MyChildDto> Children {get; set;}
}
公共类MyParentDto
{
公共int Id{get;set;}
公共列表子项{get;set;}
}
首先你不应该输入mychildtos
。它在这里没有增加任何价值。父类型应简单地键入子类
,作为列表
:
public class MyParentDto
{
public int Id {get; set;}
public List<MyChildDto> Children {get; set;}
}
公共类MyParentDto
{
公共int Id{get;set;}
公共列表子项{get;set;}
}
因为为了举例,我简化了代码;为了便于讨论,假设MyChildTos是必要的。@Andrew您应该使其不必要。找到一种方法来完成该类型正在做的任何事情,而无需子类化List
。正如您自己已经看到的,您完全不能使用该类型。在不知道您的实际问题是什么的情况下,我们无法解释您应该如何实际解决它;为了便于讨论,假设MyChildTos是必要的。@Andrew您应该使其不必要。找到一种方法来完成该类型正在做的任何事情,而无需子类化List
。正如您自己已经看到的,您完全不能使用该类型。在不知道您的实际问题是什么的情况下,我们无法解释您实际上应该如何解决它。您是否尝试过重载隐式cast运算符?(即公共静态隐式运算符mychildtos(列表项){返回新的mychildtos(项);})是否尝试重载隐式强制转换运算符?(即公共静态隐式运算符mychildtos(列表项){返回新的mychildtos(项);})