Я пишу службу WCF с EF. Моя проблема возникает при попытке вернуть дочерние объекты клиента. Ниже пример кода: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, поэтому, пожалуйста, помогите мне. Thanx.
Так что я нашел, как исправить проблему. Просто нужно было пометить ссылки клиентов от BankAccount в IgnoreDataMember
[IgnoreDataMember]
public virtual Customer Customer { get; set; }
и DIABLE ProxyCreation в MyDbContext конструктору.
this.Configuration.ProxyCreationEnabled = false;
Совет: вместо того, чтобы бросать исключение с помощью if-statement, просто используйте «return customer.Single();», который выкинет его для вас. Один должен использоваться, если вы ожидаете ровно одного совпадения. – cederlof
Это потому, что свойства навигации являются виртуальными. См. [Этот ответ] (http://stackoverflow.com/a/15822764/704144). –