【问题标题】:Entity Framework Through WCF Navigation Properties Not Populating实体框架通过 WCF 导航属性未填充
【发布时间】:2012-01-25 10:02:47
【问题描述】:

我看过类似的问题,但还没有找到解决方案。我试过使用

  1. .Include("")
  2. .Load()

但是当我通过 WCF 服务检索它们时,我的导航属性仍然​​是空的。

这是我的实体:

public class Person
{
    public int PersonID { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Address> Addresses { get; set; }

    public Person()
    {
        this.Addresses = new List<Address>();
    }
}

public class Address
{
    public int AddressID { get; set; }
    public string AddressLine1 { get; set; }
    public virtual ICollection<Person> Residents { get; set; }

    public Address()
    {
        this.Residents = new List<Person>();
    }
}

使用 fluent API 我声明这两个实体分别有许多地址/居民。我的 WCF 服务代码如下所示:

[ServiceBehavior(IncludeExceptionDetailInFaults = true)]
public class Repository : DataService<EFEntitiesDataContext>
{
    // This method is called only once to initialize service-wide policies.
    public static void InitializeService(DataServiceConfiguration config)
    {
        config.UseVerboseErrors = true;

        config.SetEntitySetAccessRule("*", EntitySetRights.All);
        config.SetServiceOperationAccessRule("*", ServiceOperationRights.All);

        config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2;
    }

    protected override EFEntitiesDataContext CreateDataSource()
    {
        EFEntitiesDataContext dataSource = new EFEntitiesDataContext();
        dataSource.Configuration.ProxyCreationEnabled = false;
        dataSource.Configuration.LazyLoadingEnabled = true;
        return dataSource;
    }

    [WebGet]
    public IList<Person> GetAllPeople()
    {
        EFEntitiesDataContext context = this.CreateDataSource();
        return context.People.Include("Addresses").Where(n => n.Addresses.Any()).ToList();
    }
}

最后,我像这样调用我的服务:

static void Main(string[] args)
{
    Uri uri = new Uri("http://localhost:49479/Repository.svc");

    RepositoryService.EFEntitiesDataContext repositoryService = new RepositoryService.EFEntitiesDataContext(uri);

    Uri uriRequest = new Uri(string.Concat(repositoryService.BaseUri, "/GetAllPeople"));
    foreach (var person in repositoryService.Execute<RepositoryService.Person>(uriRequest))
    {
        System.Console.WriteLine("Name: " + person.Name + ", Addresses: " + person.Addresses.Count.ToString());
    }

    System.Console.ReadKey();
}

有什么想法吗?

【问题讨论】:

  • 这些地址是在服务器端(GetAllPeople())还是仅在客户端(Main)缺失?顺便说一句:我认为设置ProxyCreationEnabled = falseLazyLoadingEnabled = true 没有意义,因为没有代理就无法进行延迟加载。但这可能与您的问题无关,因为您使用的是带有 Include 的急切加载。

标签: c# asp.net entity-framework-4 wcf-data-services


【解决方案1】:

默认情况下不展开导航属性。而且服务器上没有办法强迫它们扩展。客户可以通过请求 /People?$expand=Addresses 轻松做到这一点。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多