如何从wcf dataservice返回相关实体

时间:2012-01-13 20:30:59

标签: json entity-framework wcf-data-services

我创建了一个WCF数据服务类,用于将查询结果返回给javascript客户端。这是我的数据服务的伪代码:

public class MyDataService : DataService<MyEntities>
{
    public static void InitializeService(DataServiceConfiguration config)
    {
        config.SetEntitySetAccessRule("*", EntitySetRights.All);
        config.SetServiceOperationAccessRule("MyGetMethod", ServiceOperationRights.All);
        config.DataServiceBehavior.MaxProtocolVersion = DataServicePRotocolVersion.V2;
    }

    [WebGet(UriTemplate = "{SomeID}"]
    public IEnumerable<Models.Customer> MyGetMethod(int? someID)
    {
        if (someID == null) throw new DataServiceException("ID not specified");

        MyEntities context = this.CurrentDataSource;
        context.ContextOptions.LazyLoadingEnabled = false;

        var q = Linq statement which queries for a collection of entities from context

        IEnumerable<Models.Customer> result = q;
        foreach (Models.Customer customer in result)
        {
            if (!customer.Contacts.IsLoaded)
                customer.Contacts.Load();
        }

        return result;
    }
}

来自客户端请求的调用导致json。当我在dataservice中调试get方法时,result会在名为WrappedRelatedEntities的属性中扩展特定的相关数据,但是在json返回给客户端时,对于该相关实体,它表示延迟。

如果要将这些相关实体返回给客户,我需要做些什么?谢谢!

1 个答案:

答案 0 :(得分:1)

使用WCF DS服务,服务器无法强制扩展导航属性。它仅在客户端要求时才有效。因此,更改服务操作以返回IQueryable,然后客户端需要将$ expand = NameOfThePropertyToExpand添加到URL。

相关问题