实体框架通过WCF导航属性不填充

时间:2012-01-25 10:02:47

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

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

  1. .Include("")
  2. .Load()
  3. 但是当我通过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>();
        }
    }
    

    使用流畅的API我分别声明两个实体HasMany的地址/居民。我的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();
    }
    

    任何想法?

1 个答案:

答案 0 :(得分:1)

默认情况下不会展开导航属性。并且服务器上无法强制它们扩展。客户可以通过请求/ People?$ expand = Addresses轻松完成。