gpt4 book ai didi

c# - 如何在 web api get 中返回 IEnumerable DbSet?

转载 作者:行者123 更新时间:2023-11-30 17:05:56 25 4
gpt4 key购买 nike

“用户”类由 Entity Framework 模型的第一个设计者自动生成。

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 将立即执行查询。

另一种选择是不处理上下文。尽管这看起来不对,但实际上您可以让数据库上下文保持事件状态,并让垃圾收集器在您不再使用任何返回的用户对象时获取它。

关于c# - 如何在 web api get 中返回 IEnumerable DbSet?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15929529/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com