1

只需一个简单的 OData Web 服务:

public class TestService : DataService<ASUTBEntities>
{
    public static void InitializeService(DataServiceConfiguration config)
    {
        config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2;
        config.SetEntitySetAccessRule("*", EntitySetRights.AllRead
             | EntitySetRights.WriteMerge
             | EntitySetRights.WriteReplace);
        config.SetServiceOperationAccessRule("*", ServiceOperationRights.All);
        config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2;
    }

    [WebGet]
    public List<Search_Result1> FindCarOwner(string searchString)
    {
        List<Search_Result1> result = new List<Search_Result1>();
        result.AddRange(CurrentDataSource.FindContragents(searchString).ToList());
        return result;
    }
}

Search_Result1 - 是一种复杂类型,由 EDMX 文件中的 Sql Server 存储过程自动生成。如果我在浏览器中输入如下内容: hxxp://MyWebService/Test.svc/FindCarOwner?searchString='SomeString' 。它返回如下内容:

<FindCarOwner xmlns="http://schemas.microsoft.com/ado/2007/08/dataservices">
    <element xmlns:p2="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata" p2:type="ASUTBModel.Search_Result1">
        <Name>
        Name of the company
        </Name>
        <ID p2:type="Edm.Int32">538175</ID>
    </element>
    ... and 3 elements more (total 4 elements)
</FindCarOwner>

但是,如果我尝试从应用程序调用此函数,它会返回容量 = 4 且计数 = 0 的列表。我这样做:

ASUTBOData.ASUTBEntities context = new ASUTBOData.ASUTBEntities(new Uri(servicePath));
context.Credentials = System.Net.CredentialCache.DefaultCredentials;
context.MergeOption = MergeOption.NoTracking;
List<Search_Result1> preresult;
try
{
    preresult = context.Execute<Search_Result1>(new Uri("hxxp://MyWebService/Test.svc/FindCarOwner?searchString='SomeString'")).ToList();
}
catch (Exception e)
{
    return null;
}

为什么应用程序无法转换接收到的值?它可以修复,还是我必须找到其他解决方案?

4

1 回答 1

0

数据服务客户端仅支持来自 Schema 的 EntityType 物化,如 OData 中所述(对我而言,它是 MyWebService/Test.svc/$metadata)。我能找到的唯一解决方案是使用 System.Net 中的 WebClient

WebClient wc = new WebClient();
wc.UseDefaultCredentials = true;

XDocument xdoc = XDocument.Parse(wc.DownloadString(new Uri(request)));
var res = xdoc.Root.Descendants( ((XNamespace)@"http://schemas.microsoft.com/ado/2007/08/dataservices") + 
                                            "element");

preresult = res.Select(xe => xe.Value).ToList();
于 2012-12-12T16:54:45.100 回答