C# 关闭代理将导致没有关联

C# 关闭代理将导致没有关联,c#,wcf,entity-framework,C#,Wcf,Entity Framework,我正在从事一个项目,我们使用WCF和实体框架。 因为WCF不能与动态代理一起工作,所以我将这一行放在我的上下文类的构造函数中: public CarBatteryEntities() : base("name=CarBatteryEntities") { base.Configuration.ProxyCreationEnabled = false; } WCF可以工作,但是我的linq查询不会返回它们的关联 这是我的代码: List<Edge> edges = edgeR

我正在从事一个项目,我们使用WCF和实体框架。 因为WCF不能与动态代理一起工作,所以我将这一行放在我的上下文类的构造函数中:

public CarBatteryEntities() : base("name=CarBatteryEntities")
{
    base.Configuration.ProxyCreationEnabled = false;
}
WCF可以工作,但是我的linq查询不会返回它们的关联

这是我的代码:

List<Edge> edges = edgeRepository.GetBatteryCenterEdges("cityname").ToList();
foreach(var e in edges)
    Console.WriteLine(e);

由于已关闭代理,您可能需要加载与的关联。

使用
Include()
执行即时加载:

using System.Data.Entity; // for Include extension method.

var results = ctx.Edges
    .Include(e => e.BatteryStation)
    .Include(e => e.BatteryStation1)
    .ToList();
或对每个实体执行显式加载:

var results = ctx.Edges.ToList();

foreach(var e in results)
{
    ctx.Entry(e).Reference(x => x.BatteryStation).Load();
    ctx.Entry(e).Reference(x => x.BatteryStation1).Load();
}

您可以按如下方式作为扩展方法来执行此操作。它是包含任何具有关系的实体的通用方法,您也可以通过使用返回要加载的导航属性的表达式对任意N个包含进行相同操作

public IQueryable<TEntity> GetAllIncluding(params Expression<Func<TEntity, object>>[] includeProperties) 
{
   IQueryable<TEntity> queryable = GetAll();
   foreach (Expression<Func<TEntity, object>> includeProperty in includeProperties) 
   {
      queryable = queryable.Include<TEntity, object>(includeProperty);
   }

   return queryable;
}
public IQueryable GetAllIncluding(参数表达式[]includeProperties)
{
IQueryable queryable=GetAll();
foreach(includeProperty中的表达式includeProperty)
{
queryable=queryable.Include(includeProperty);
}
返回可查询;
}

能否列出
GetBatteryCenter
的源代码?在
包含(e=>e.BatteryStation)
上,它返回一个错误,其中“无法将lambda表达式转换为stringIt类型。它是System.Data.Entity中的扩展方法。与使用字符串的版本相比,此版本更受欢迎,因为它支持重构,并且如果缺少其中一个属性,将导致编译时错误。答案已更新。
public IQueryable<TEntity> GetAllIncluding(params Expression<Func<TEntity, object>>[] includeProperties) 
{
   IQueryable<TEntity> queryable = GetAll();
   foreach (Expression<Func<TEntity, object>> includeProperty in includeProperties) 
   {
      queryable = queryable.Include<TEntity, object>(includeProperty);
   }

   return queryable;
}