2010-03-29 8 views
1

저는 C#에 익숙하지 않고 다음에 붙어 있습니다. LINQ를 사용하여 ADO.NET 엔터티 개체를 쿼리하는 Silverlight 웹 서비스가 있습니다. 예컨대 :일반 목록 형변환 문제

[OperationContract] 
public List<Customer> GetData() 
{ 
    using (TestEntities ctx = new TestEntities()) 
    { 
     var data = from rec in ctx.Customer 
        select rec; 
     return data.ToList(); 
    } 
} 

이 잘 작동하지만 내가 원하는 것은이 더 추상적를 확인하는 것입니다. 첫 번째 단계는 List<EntityObject>를 반환하는 것입니다 그러나 이것은 컴파일러 오류, 예컨대 : 제공

[OperationContract] 
public List<EntityObject> GetData() 
{ 
    using (TestEntities ctx = new TestEntities()) 
    { 
     var data = from rec in ctx.Customer 
        select rec; 
     return data.ToList(); 
    } 
} 

오류입니다 : 내가 뭘 잘못

Error 1 Cannot implicitly convert type 'System.Collections.Generic.List<SilverlightTest.Web.Customer>' to 'System.Collections.Generic.IEnumerable<System.Data.Objects.DataClasses.EntityObject>'. An explicit conversion exists (are you missing a cast?) 

? 제네릭 형식의 공분산이 지원되지 않기 때문에 EntityObject에서 Customer 상속이 List<Customer>List<EntityObject>에서 상속하지 않더라도

감사합니다,

AJ

답변

3

는 (C# 4.0, 공분산은 인터페이스가 지원되지 않지만, IList<T>). 당신이 유형 List<EntityObject>의 변수에 List<Customer>을 할당 할 수 있다면

것은, 당신이 그런 일을 할 수있는 것 :

List<EntityObject> list = new List<Customer>(); 
list.Add(new Product()); // assuming Product inherits from EntityObject 

이 코드는 분명히 고장 : 당신이 List<Customer>Product를 추가 할 수 없습니다 . 이

0
[OperationContract] 
public List<EntityObject> GetData() 
{ 
    using (TestEntities ctx = new TestEntities()) 
    { 
     var data = from rec in ctx.Customer 
        select (EntityObject)rec; 
     return data.ToList(); 
    } 
} 

당신이 D는 그것은 공분산이라고 B.에서 파생 만 어레이와 함께 작동하는 경우에도 목록에 목록을 시전 할 수 허용되지 않는 이유입니다. C# 4.0에 완전히 소개 될 것입니다.

0

var 데이터에는 Customer 개체가 포함되어 있으며 반환 값은 EntityObjects의 목록입니다.

당신이 그들을 캐스팅해야합니다 :

data.ConvertAll(obj => (EntityObject) obj).ToList(); 
+0

나는이를 좋아하지만, 데이터가 ConvertAll 방법을 가지고 있지 않기 때문에 그것은 나를 위해 작동하지 않았다. –

0

당신은 data.Cast<EntityObject>().ToList(); 너머

data.Cast<EntityObject>().ToList();