开发者

WCF + EF 4.1 Eager Loading and Serialization Problem

开发者 https://www.devze.com 2023-04-07 16:17 出处:网络
The simple case where my OperationContract implementation is like: public List<Directory> GetDirectories(bool includeFiles)

The simple case where my OperationContract implementation is like:

public List<Directory> GetDirectories(bool includeFiles)
{
    if (includeFiles)
    {
        return this.db.Directories.Include(e => e.Files).ToList();
    }
    else
    {
        return this.db.Directories.ToList();
    }
}

where GetDirectories(false); works perfectly ok and GetDirectories(true); throws a CommunicationObjectFaultedException with message:

The communication object, System.ServiceModel.Channels.ServiceChannel, cannot be used for communication because it is in the Faulted state.

Obviously my File entities have reference to Directory entities, and the Directory entities have a list of files. First I thought this would be the typical c开发者_如何学Cyclic reference trap but I get no signs of it in the exception message. Any ideas on this problem?


It will be cyclic reference trap (here is something about this topic) and reason for your CommunicationObjectFaultedException will be something like:

using (var client = new ServiceClient())
{
    data = client.GetDirectories(true);
}

The reason is that unhandled exception has faulted the channel and using is trying to call Close on that faulted channel - it is invalid transition in channel state machine (and one big WCF strangeness) resulting it the exception you mentioned. There are many ways to avoid it but the basis is:

ServiceClient client = null;

try
{
    client = new ServiceClient();
    data = client.GetDirectories(true);
}
finally
{
    if (client != null)
    {
        if (client.State == CommunicationState.Faulted) 
        {
            client.Abort();
        } 
        else 
        {
            client.Close();
        }
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消