2012-05-08 4 views
1

EF를 사용하여 WCF 서비스를 작성하고 있습니다. 고객 엔터티의 하위 항목을 반환하려고 할 때 문제가 발생합니다. 샘플 코드 아래 :WCF Entity Framework에서 엔터티 자식을 액세스 할 수 없습니다.

[DataContract] 
public class Customer 
{ 
     [Key] 
     [DataMember] 
     public int CustomerID { get; set; } 

     [DataMember] 
     public string FirstName { get; set; } 

// Customer has a collection of BankAccounts 
     [DataMember] 
     public virtual ICollection<BankAccount> BankAccounts { get; set; } 
} 

[DataContract(IsReference = true)] 
    public class BankAccount 
    { 
     [Key] 
     [DataMember] 
     public int BankAccountID { get; set; } 

     [DataMember] 
     public int Number { get; set; } 

     // virtual property to access Customer 
     //[ForeignKey("CustomerID")] 
     [Required(ErrorMessage = "Please select Customer!")] 
     [DataMember] 
     public int CustomerID { get; set; } 

     [DataMember] 
     public virtual Customer Customer { get; set; } 
    } 

오류 내가 얻을 :

An error occurred while receiving the HTTP response to http://localhost:8732/Design_Time_Addresses/MyServiceLibrary/MyService/. This could be due to the service endpoint binding not using the HTTP protocol. This could also be due to an HTTP request context being aborted by the server (possibly due to the service shutting down). See server logs for more details. 

내가 전화 서비스 기능 :

public Customer GetCustomer(int customerId) 
     { 
      var customer = from c in dc.Customers 
          where c.CustomerID == customerId 
          select c; 
      if (customer != null) 
       return customer.FirstOrDefault(); 
      else 
       throw new Exception("Invalid ID!"); 

     } 

내가 그것을 디버깅을 시도하고,이 함수는를 반환 고객 및 그것도 어린 이용 BankAccounts, 나는 또한 게으른 로딩을 비활성화했습니다. 나는 내가이 줄을

public virtual ICollection<BankAccount> BankAccounts { get; set; } 

형태로 고객 클래스를 주석 경우, 모든 것이 내가는 BankAccount를 얻을 수없는 것을 제외하고, 그것은 단지 고객을 반환 작동하는 것을 발견했다. WCF에 처음 왔으므로 도와주세요. 고맙습니다.

그래서 문제를 해결하는 방법을 찾았습니다. 그냥 IgnoreDataMember

[IgnoreDataMember] 
public virtual Customer Customer { get; set; } 

및 MyDbContext 생성자 줘 ProxyCreation로는 BankAccount에서 고객 레퍼런스를 표시했다.

this.Configuration.ProxyCreationEnabled = false; 
+0

팁 : if 문을 사용하여 예외를 throw하는 대신 "return customer.Single();"를 사용하면 문제가 해결됩니다. 단 하나의 일치가 정확히 예상 될 때 싱글을 사용해야합니다. – cederlof

+0

탐색 속성이 가상이기 때문입니다. [이 답변] (http://stackoverflow.com/a/15822764/704144)을 참조하십시오. –

답변

0

이 기능은 열심히로드하는 것을 사용하지 않기 때문에 고객과 고객의 계정을 모두 반환하려면 지연 적재가 필요합니다. 당신이 게으른 로딩을 사용하지 않으려면 당신은 사용해야합니다

dc.Customers.Include("BankAccounts") 

어쨌든 당신의 주요 문제는 순환 참조 (고객 계정 및 계정 고객에게 역 참조가 참조가 있습니다) 기본 WCF 직렬화를 중단 할 수 있습니다. 그들의 존재에 관해서는 inform serializer이어야합니다.

+0

응답 해 주셔서 감사합니다. 그러나 문제는 계속 발생합니다. – Razuro

+0

답변에서 제공 한 링크를 따라 갔습니까? –

+0

예, 내가 거기서 그림을 보았는데, EF4 엔티티를 직렬화 할 수 없다는 것을 보여주었습니다. 따라서 광산을 확인하고 광산이 동일하게 보였으므로 ProxyCreation을 비활성화했습니다. 아직도 나는 ProxyCreation이하는 일을 완전히 이해하지 못했다. 고맙습니다. – Razuro

관련 문제