为什么实体Framewok方法“.AsEnumerable()”什么都不返回?

时间:2016-08-25 09:02:31

标签: c# angularjs asp.net-web-api

我使用Entity Framework 6.0.0.0,方法是Database First。 我有三个表ClientAccountDoc。一个Client有许多DocsAccounts。关系是一对多Client表:

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;
    });
}

Get的{​​{1}}方法获取数据(它返回NOTHING。没有客户端):

Web API

但是, [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()

但是,AngularJS方法正在调用retutn db.Client.ToList();// it returns all necessary data

非常感谢任何帮助。

我在$http.get('/api/Search/').error(...)的{​​{1}}窗口中看到的内容: enter image description here

2 个答案:

答案 0 :(得分:1)

在我看来,将对象序列化为xml或json时出错。 这通常是由数据对象中的循环引用引起的。例如,您的客户引用帐户和帐户引用客户端。如果是这种情况,序列化程序将继续序列化对象,直到它耗尽内存

解决这个问题有几个选择。

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

答案 1 :(得分: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转换为List   为了这个目的。使用AsEnumerable vs.的优势   ToList是AsEnumerable不执行查询。 AsEnumerable   保留延迟执行并且不构建通常无用的   中间名单。

     

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

     

AsQueryable可用于使可枚举集合接受   LINQ语句中的表达式。有关详细信息,请参见此处。

这可以解释为什么您收到错误,考虑坚持列表,或尝试AsQueryable()并查看是否有效而不是AsEnumerable()