繁体   English   中英

如何在web api中返回IEnumerable DbSet?

[英]How to return IEnumerable DbSet in web api get?

“user”类由实体框架模型第一个desinger自动生成。

public partial class user
{
    public user()
    {
        this.distributorDevice = new HashSet<distributorDevice>();
        this.managerDevice = new HashSet<managerDevice>();
        this.logUserLogin = new HashSet<logUserLogin>();
        this.logUserOperates = new HashSet<logUserOperates>();
        this.clientApp = new HashSet<clientApp>();
    }

    public int Id { get; set; }
    public string name { get; set; }
    public byte[] password { get; set; }
    public bool isActive { get; set; }
    public System.DateTime RegisterTime { get; set; }
    public int permissionId { get; set; }
    public System.DateTime lastLoginTime { get; set; }

    public virtual permission permission { get; set; }
    public virtual ICollection<distributorDevice> distributorDevice { get; set; }
    public virtual ICollection<managerDevice> managerDevice { get; set; }
    public virtual ICollection<logUserLogin> logUserLogin { get; set; }
    public virtual ICollection<logUserOperates> logUserOperates { get; set; }
    public virtual ICollection<clientApp> clientApp { get; set; }
    public virtual customerDevice customerDevice { get; set; }
}

如果我这样写的话

 public class UserController : ApiController
 {
 public IEnumerable<user> Get()
    {
        List<user> users = new List<user>();
        return user;
    }
 }

当我在资源管理器中访问“localhost:3700 / api / user”时,它可以工作。

<ArrayOfuser xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/UpdateServer.Model"/>

如果我这样写的话

    public IEnumerable<user> Get()
    {
        using (var mydb = new ModelContainer())
        {
            return mydb.userSet.AsEnumerable();
        }
    }

当我在资源管理器中访问“localhost:3700 / api / user”时,收到错误消息:

103 (net::ERR_CONNECTION_ABORTED)

按照建议,我应该使用ToList()而不是asEnumerable,我改变这样的代码

using (var mydb = new ModelContainer())
        {
            var users = mydb.userSet.ToList();
            return users;
        }

但仍然在资源管理器中出现同样的错误

103 (net::ERR_CONNECTION_ABORTED)

我在中添加一个中断

return users;

发现用户已经从DB获取数据,但没有正确返回客户端。

我做了更多的测试,我添加了一个权限名称为“Admin”的用户,如果我使用下面的代码,则没有找到用户,并且它正确响应客户端。

var users = mydb.userSet.Where(p=>p.permission.name == "Administrator").ToList();
return users;

如果我这样写

var users = mydb.userSet.Where(p=>p.permission.name == "Admin").ToList();
return users;

它未能返回客户端,给出错误

103 (net::ERR_CONNECTION_ABORTED)

EF使用延迟加载。 这意味着在您尝试使用结果之前,EF实际上不会调用数据库。

要解决此问题,您可以使用ToList() AsEnumerable ToList不同,它会立即执行查询。

另一种选择是不处理上下文。 虽然这可能看起来有误,但实际上可以让db context保持活动状态,让垃圾收集器在您不再使用任何返回的用户对象时获取它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM