![](/img/trans.png)
[英]It is possible to access a parent entity through navigation properties in Entity Framework?
[英]Entity Framework Through WCF Navigation Properties Not Populating
我看過類似的問題,但尚未找到解決方案。 我試過使用
.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>();
}
}
我使用流利的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();
}
有任何想法嗎?
導航屬性默認情況下不展開。 而且服務器上沒有辦法強迫它們擴展。 客戶端可以通過請求/ People?$ expand = Addresses輕松地做到這一點。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.