我正在使用 WCF数据服务类,它通过 OData 协议公开实体框架模型,如下所示:
public class Service : EntityFrameworkDataService<MyEntities>
{
public static void InitializeService(DataServiceConfiguration config)
{
config.UseVerboseErrors = true;
config.SetEntitySetAccessRule("*", EntitySetRights.All);
config.SetServiceOperationAccessRule("*", ServiceOperationRights.All);
config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V3;
}
}
我通过网络解决方案中的服务参考来使用此服务。我遇到了包括实体的所有导航属性的问题。我不能使用以下语法,因为我不知道用户可能要求的实体类型:
我不能使用
MyEntities.Customer.Expand("Address");
或
MyEntities.Customer.Include("Address");
我目前正在做的是使用$ expand = Entity1,Entity2语法构建一个URI字符串,然后针对我的服务执行该字符串,如下所示:
public static QueryOperationResponse<object> GetList(string entitySetName, params string[] preloads)
{
StringBuilder stringBuilder = new StringBuilder();
string queryString = string.Empty;
object result = null;
Uri dataAccessURI;
stringBuilder.Append(ServiceReferenceURI.AbsoluteUri);
stringBuilder.Append(entitySetName);
if (preloads != null)
{
for (int i = 0; i <= preloads.Length - 1; i++)
{
queryString = i == 0 ? "?$expand=" : ",";
stringBuilder.AppendFormat("{0}{1}", queryString, preloads[i]);
}
}
dataAccessURI = new Uri(stringBuilder.ToString());
try
{
result = TitanEntities.Execute<object>(dataAccessURI, "GET", true);
}
catch (Exception ex)
{
// log any errors to the console
WriteConsoleMessage(ex.Message, DataAccessEventType.Error);
}
return (QueryOperationResponse<object>)result;
结果URI字符串与此类似:
http://192.168.0.196/Service.svc/AliquotPreparation?$expand=Aliquot,AliquotPrepBatch,AnalysisPreparationMethod,Unit,Employee,Unit,PreparationMethod,State
对我而言,这是一个糟糕的实施。尽管如此,这是我能想到的。问题是,如果有很多导航属性,$ expand命令会变得太长而URI达到它的字符限制!
那么如何通过服务引用实现这一点呢?我非常感谢别人的帮助!!!