【发布时间】:2012-01-25 10:02:47
【问题描述】:
我看过类似的问题,但还没有找到解决方案。我试过使用
-
.Include("") -
.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 = false和LazyLoadingEnabled = true没有意义,因为没有代理就无法进行延迟加载。但这可能与您的问题无关,因为您使用的是带有Include的急切加载。
标签: c# asp.net entity-framework-4 wcf-data-services