Новичок, пожалуйста, несите меня, как только я начал вчера с WCF.WCF с ошибкой Entity Framework Часть II
Я использую Northwind для данных и добавляю только заказчиков, заказы, детали заказа и продукты к модели, поэтому ничего фантастического.
Когда я запускаю приложение и вызываю Test и устанавливаю точку останова, значение для продуктов есть, и оно завершается без ошибок. Если я затем попытаюсь вызвать GetMaxQuantityByOrderID (10248), я получу ошибку, указанную внизу. Почему Test() работает и тот же метод WITHIN Test() НЕ работает? Я даже добавил еще один (Test1(), точно такой же, как Test, за исключением того, что возвращает строку: x.ProductName, которое правильно отображает Queso Cabrales). Кажется странным, что метод, который вызывается внутри другого, работает, но вызов его напрямую вызывает исключение.
Еще одна проблема, с которой я столкнулся, заключается в том, что IEnumerable GetOrders() работает только при добавлении .ToList(). Без него (или с .AsEnumerable()), я получаю сообщение об ошибке (Экземпляр ObjectContext был удален и больше не может использоваться для операций, требующих подключения.), хотя для ленивой загрузки установлено значение False. Какова логика этого?
IServiceTest.cs
using System.Collections.Generic;
using System.ServiceModel;
namespace WcfTestServiceLibrary
{
[ServiceContract]
public interface IServiceTest
{
[OperationContract]
IEnumerable<Orders> GetOrders();
[OperationContract]
IEnumerable<Customers> GetCustomers();
[OperationContract]
Customers GetCustomerByID(string customerID);
[OperationContract]
Orders GetOrderByID(int id);
[OperationContract]
IEnumerable<Order_Details> GetOrderDetailsByOrderID(int id);
[OperationContract]
Order_Details GetMaxQuantityByOrderID(int id);
[OperationContract]
void Test();
}
}
ServiceTest.cs
using System.Collections.Generic;
using System.Linq;
namespace WcfTestServiceLibrary
{
public class ServiceTest : IServiceTest
{
public IEnumerable<Orders> GetOrders()
{
using (var ctx = new NWEntities())
{
return (from o in ctx.Orders.Include("Order_Details.Products").Include("Customers")
select o).ToList();
}
}
public IEnumerable<Customers> GetCustomers()
{
using (var ctx = new NWEntities())
{
return (from c in ctx.Customers
select c);
}
}
public Customers GetCustomerByID(string customerID)
{
return (from c in GetCustomers()
where c.CustomerID == customerID
select c).FirstOrDefault();
}
public Orders GetOrderByID(int id)
{
IEnumerable<Orders> orders = GetOrders();
return (from o in orders
where o.OrderID == id
select o).FirstOrDefault();
}
public IEnumerable<Order_Details> GetOrderDetailsByOrderID(int id)
{
return GetOrderByID(id).Order_Details;
}
public Order_Details GetMaxQuantityByOrderID(int id)
{
Orders order = GetOrderByID(id);
return order == null ? null : order.Order_Details.OrderByDescending(x => x.Quantity).FirstOrDefault();
}
public void Test()
{
const int orderID = 10248;
var oq = GetMaxQuantityByOrderID(orderID);
var x = oq.Products;
}
}
}
Ошибка:
An error occurred while receiving the HTTP response to http://localhost:8732/Design_Time_Addresses/WcfTestServiceLibrary/Service1/. 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.
Server stack trace:
at System.ServiceModel.Channels.HttpChannelUtilities.ProcessGetResponseWebException(WebException webException, HttpWebRequest request, HttpAbortReason abortReason)
at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
at System.ServiceModel.Channels.RequestChannel.Request(Message message, TimeSpan timeout)
at System.ServiceModel.Channels.ClientReliableChannelBinder`1.RequestClientReliableChannelBinder`1.OnRequest(TRequestChannel channel, Message message, TimeSpan timeout, MaskingMode maskingMode)
at System.ServiceModel.Channels.ClientReliableChannelBinder`1.Request(Message message, TimeSpan timeout, MaskingMode maskingMode)
at System.ServiceModel.Channels.ClientReliableChannelBinder`1.Request(Message message, TimeSpan timeout)
at System.ServiceModel.Security.SecuritySessionClientSettings`1.SecurityRequestSessionChannel.Request(Message message, TimeSpan timeout)
at System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message message, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
Exception rethrown at [0]:
at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
at IServiceTest.GetMaxQuantityByOrderID(Int32 id)
at ServiceTestClient.GetMaxQuantityByOrderID(Int32 id)
Inner Exception:
The underlying connection was closed: An unexpected error occurred on a receive.
at System.Net.HttpWebRequest.GetResponse()
at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
Inner Exception:
Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
at System.Net.PooledStream.Read(Byte[] buffer, Int32 offset, Int32 size)
at System.Net.Connection.SyncRead(HttpWebRequest request, Boolean userRetrievedStream, Boolean probeRead)
Inner Exception:
An existing connection was forcibly closed by the remote host
at System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags)
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
Если я изменяю IQueryable, я получаю сообщение об ошибке Экземпляр ObjectContext была отчуждена и больше не могут быть использованы для операций, требующих соединения. Каков правильный способ работы с услугами WCF? Я не понимаю, что позволит мне настроить трассировку. Как я уже сказал, я только что начал с WCF 2 дня назад. –
Я добавил некоторую информацию о трассировке и EF. –
Проблема возникает только в тестовом клиенте WCF. Если я не использую клиента и использую страницу asp.net для результатов, она работает. –