2016-08-25 70 views
1

我使用Entity Framework 6.0.0.0,方法是Database First。 我有三个表Client,Account,Doc。一个Client有许多DocsAccounts。关系是一对多Client表:为什么Entity Framewok方法“.AsEnumerable()”不返回任何内容?

public partial class Client 
{ 
    public Client() 
    { 
     this.Account = new HashSet<Account>(); 
     this.Doc = new HashSet<Doc>(); 
    } 

    public int ClientId { get; set; } 
    public string Name { get; set; } 

    public virtual ICollection<Account> Account { get; set; } 
    public virtual ICollection<Doc> Doc { get; set; } 
} 

AngularJs代码片段从WebApi取数据:

angular.module("app", []).controller("searchController", function ($scope, $http) { 

    //Used to get and display the data 
    $http.get('/api/Search/').success(function (data) { 
     debugger; 
     $scope.searchs = data; 
     $scope.loading = false; 
    }) 
    .error(function() { 
     debugger; 
     $scope.error = "An Error has occured while loading posts!"; 
     $scope.loading = false; 
    }); 
} 

方法Web APIGet取数据(它没有返回值没有客户。):

[HttpGet] 
    public IEnumerable<Client> Get() 
    { 
     private ClientDBEntities db = new ClientDBEntities(); 
     retutn db.Client.AsEnumerable();// it returns NOTHING. There is no clients 

    } 

然而,$http.get('/api/Search/').success(function (data)调用,如果我改变这种方法返回IEnumerable<string>

[HttpGet] 
    public IEnumerable<Client> Get() 
    { 
     List<string> list = new List<string>(){"1", "2", "3"}; 
     return list;    
    } 

我的问题是为什么db.Client.AsEnumerable()返回什么?我试图将此代码更改为:

retutn db.Client.ToList();// it returns all necessary data 

然而,AngularJS方法调用$http.get('/api/Search/').error(...)

任何帮助将不胜感激。

我在Watch窗口Visual Studio看到了什么: enter image description here

+0

你得到的错误是什么? –

+0

@AmitKumarGhosh没有错误,只是它的工作原理都可以。我附上了我的观察窗口,以查看我在每个查询中得到的结果。谢谢。 – StepUp

+0

在我看来你正试图返回数据库对象与延迟加载。当反序列化为json时,如果有循环引用,这可能会导致内存不足异常。 –

回答

1

,而不是看起来对我来说有一个错误的序列化对象为XML或json。 这通常是由数据对象中的循环引用引起的。例如,您的客户引用帐户和帐户引用客户端。如果是这种情况,串行器将保持序列化对象,直到它耗尽内存

要解决这个问题,有几个选项。

  1. 只通过将其转换为新对象(viewmodel)来返回您真正需要的数据。
  2. 为您的查询禁用延迟加载,这将阻止您为该查询加载帐户/文档对象,请参阅(Entity Framework: How to disable lazy loading for specific query?)。
  3. 使序列化程序忽略导致自引用循环的属性。 (用于序列化为json使用属性[JsonIgnore])
0

你能尝试匹配与List数据类型函数的返回值?

例如:

[HttpGet] 
public List<Client> Get() 
{ 
    private ClientDBEntities db = new ClientDBEntities(); 
    retutn db.Client.ToList(); 
} 

更新 这里是一个有用的链接:What's the difference(s) between .ToList(), .AsEnumerable(), AsQueryable()?

基本上,有关该案件的关键部分是这样的:

ToList - 这将IEnumerable转换为列表 - 为此目的也经常使用 。使用AsEnumerable与 ToList的优点是AsEnumerable不执行查询。 AsEnumerable 保留延迟执行并且不会构建一个通常无用的中间列表 。

另一方面,当需要强制执行LINQ查询时,ToList可以成为一种方法。

AsQueryable可用于使可枚举集合在LINQ语句中接受 表达式。详情请看这里。

这也许可以解释为什么你会得到一个错误,认为坚持名单,或尝试AsQueryable(),看其是否正常工作的AsEnumerable()

+0

yeap,我试过了。但是,调用'http http.get('/ api/Search /')。error(...)'。但是我想''http.get('/ api/Search /')。success(function(data){}'被调用,谢谢你的试用 – StepUp

+0

你可以验证你的'ClientDBEntities()'确实返回什么?也许你可以显示该函数的代码来帮助我理解这个问题。 –

+0

请查看我附加的图像问题。 – StepUp

相关问题