OData 控制器不从联接(包含)表中返回数据


public class Account
{
[Key]
[StringLength(80)]
public string AccountID { get; set; } = string.Empty;
[StringLength(255)]
public string Name { get; set; } = string.Empty;
[StringLength(255)]
public string Email { get; set; } = string.Empty;
[ForeignKey(nameof(AccountID))]
public virtual ICollection<Relation> Relations { get; set; }
}
public class Role
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
public long RoleID { get; set; } = -1;
[StringLength(80)]
public string RoleName { get; set; } = string.Empty;
}
public class Relation
{
[Key]
[StringLength(80)]
public string AccountID { get; set; } = string.Empty;
[Required]
public long RoleID { get; set; } = 0;
[ForeignKey(nameof(RoleID))]
public virtual Role Role { get; set; }
}
public class AccountsController : ODataController
{
private readonly DS2DbContext _context;
public AccountsController(DS2DbContext context)
{
_context = context;
}
[EnableQuery(PageSize = 15)]
public IQueryable<Account> Get()
{
var q = _context.accounts
.Include(e => e.Relations)
.ThenInclude(e => e.Role)
;
// debug code
var l = q.ToList();
var i = l.FirstOrDefault();
return q;
}
}

测试代码显示正在读取包含的表中的数据,但它没有发送到客户端:

{@odata.context: "https://localhost:44393/DS/$metadata#Accounts", @odata.count: 2,…}
@odata.context: "https://localhost:44393/DS/$metadata#Accounts"
@odata.count: 2
value: [,…]
0: {AccountID: "0", Firstname: "A", Lastname: "H", Email: "a.h@b.g",…}
AccountID: "0"
Department: "WD"
Email: "a.h@b.g"
Firstname: "A"
Lastname: "H"
1: {AccountID: "1", Firstname: "D", L: "M", Email: "d.m@b.g",…}
AccountID: "1"
Department: "WD"
Email: "d.m@b.g"
Firstname: "D"
Lastname: "M"

缺少Account.Relationship和Relation.Role中的数据。我需要更改或添加哪些内容才能使其工作?

我自己找到了解决方案。不是在控制器中包含表,而是让OData框架通过向其传递$expand参数来完成工作

?$expand=Relations($expand=Role) 

到服务器请求。这将使;级联";include,其中对于每个Account实体,从relationship表读取所有Relations,从roles表读取每个Relation的Role属性。

控制器的Get((方法只需返回_context.accounts:

[EnableQuery(PageSize = 15)]
public IQueryable<Account> Get()
{
return _context.accounts;
}

最新更新