我想查询数据库并获取一个包含所有内部列表的运动对象,但是由于某种原因,我丢失了,所以选择仅在列表中深入2个级别,任何更深的内容,并且lists属性的值为{{ 1}}, 结构示例
null
我以此在MyAppContext文件中创建属性
public class Sports
{
public int id { get; set; }
public string name { get; set; }
public List<League> leagues { get; set; }
}
public class League
{
public int id { get; set; }
public string name { get; set; }
public string description { get; set; }
public List<Team> teams { get; set; }
}
public class Team
{
public int id { get; set; }
public string name { get; set; }
public string successrate { get; set; }
public List<Player> players { get; set; }
}
public class Player
{
public int id { get; set; }
public string name { get; set; }
public int age { get; set; }
}
现在,当我使用select或linq或其他尝试方式调用项目时,运动对象始终是2维的,这意味着它的深度不超过嵌套列表中的两个层次!使用public DbSet<Sports> sports { get; set; }
的结果示例为var sport=db.Sports.First()
或如果我使用select()
{"id":1,"name":"Football","leagues":null}
我仍然没有获得完整的信息 var sportQuery = db.sports.Select(
s=>new Sports(){
id=s.id,
leagues=s.leagues,
name=s.name
}).First();
这是为什么!以及如何获得像这样的完整物体
{"id":1,"name":"Football","leagues":[{"id":1,"name":"fc","description":"Some Leauge","teams":null},{"id":2,"name":"al","description":"League","teams":null}]}
我已经被困了好几天,请给予任何帮助
答案 0 :(得分:0)
使用Include()
和thenInclude()
解决的问题
https://docs.microsoft.com/en-us/ef/core/querying/related-data
但是,这并不能解释为什么Select()
只加载一个列表属性很深,而且看来我应该能够使用select only或linq加载对象
答案 1 :(得分:0)
尝试以下操作:
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
DataBase db = new DataBase();
var sportQuery = db.sports.Select(s=> s.leagues.Select(l => l.teams.Select(t => t.players.Select(p => new {
playerid = p.id,
playerName = p.name,
playerAge = p.age,
teamId = t.id,
teamName = t.name,
teamSucessrate = t.successrate,
leagueId= l.id,
leagueName= l.name,
leagueDescription = l.description,
sportId = s.id,
sportName = s.name
}))
.SelectMany(p => p))
.SelectMany(t => t))
.SelectMany(l => l)
.ToList();
}
}
public class DataBase
{
public List<Sports> sports { get; set;}
}
public class Sports
{
public int id { get; set; }
public string name { get; set; }
public List<League> leagues { get; set; }
}
public class League
{
public int id { get; set; }
public string name { get; set; }
public string description { get; set; }
public List<Team> teams { get; set; }
}
public class Team
{
public int id { get; set; }
public string name { get; set; }
public string successrate { get; set; }
public List<Player> players { get; set; }
}
public class Player
{
public int id { get; set; }
public string name { get; set; }
public int age { get; set; }
}
}