ASP.NET json对象不包含自定义对象

时间:2018-10-26 13:06:59

标签: asp.net json asp.net-web-api

当用户到达某个位置时,他会收到一个问题。因此,我有一个“问题”类和一个“位置”类。但是,当我检索位置时,Question参数始终为null。 这似乎是整个项目的问题,因为相同的问题在其他地方重复出现(在这里,“游戏”有一个“团队”列表,但团队总是空着的。)

在初始化数据库时创建对象:

public static void Initialize(DBContext context)
    {
        context.Database.EnsureCreated();
        if (!context.Games.Any())
        {
            var teams = new List<Team>();
            var team1 = new Team()
            {
                TeamName = "Kwizmasterz",
                TotalPoints = 0,
                TotalBoobyTraps = 2
            };
            var team2 = new Team()
            {
                TeamName = "Xesennettet",
                TotalPoints = 0,
                TotalBoobyTraps = 2
            };
            teams.Add(team1);
            teams.Add(team2);

            var game = new Game()
            {
                GameCode = "X35H0",
                team = teams
            };

            context.Games.Add(game);
            context.SaveChanges();
        }

        if (!context.Locations.Any())
        {
            var que = new Question()
            {
                QuestionText = "How much is 2 + 2?",
                Answer = "4",
                IsSolved = false,
                Points = 1000000
            };
            var loc = new Location()
            {
                LocationName = "LocationName",
                Latitude = 50.2299036,
                Longitude = 5.4163052,
                Question = que,
                IsBoobyTrapped = false
            };

            context.Locations.Add(loc);
            context.SaveChanges();
        }
    }

位置信息类:

public class Location
{
    public int LocationID { get; set; }
    public string LocationName { get; set; }
    public double Latitude { get; set; }
    public double Longitude { get; set; }
    public Question Question { get; set; }
    public bool IsBoobyTrapped { get; set; }
    public int VictorTeamID { get; set; } = -1;
}

问题类别:

public class Question
{
    public int QuestionID { get; set; }
    public int QuestionType { get; set; } // 1 = Question - Answer

    public string QuestionText { get; set; }
    public int Points { get; set; }
    public bool IsSolved { get; set; }

    public string Answer { get; set; }
}

控制器类:

[Route("api/v1")]
public class GameController : Controller
{
    private readonly DBContext context;
    public GameController(DBContext context)
    {
        this.context = context;
    }

    public IActionResult Index()
    {
        return View();
    }

    [Route("location")]
    [HttpPost]
    public IActionResult postGame([FromBody] Location newLocation)
    {
        newLocation.LocationID = context.Games.Count();
        context.Locations.Add(newLocation);

        return Created("", newLocation);
    }

    [Route("location")]
    [HttpGet]
    public List<Location> getLocations()
    {
        return context.Locations.ToList();
    }

    [Route("location/{id}")]
    [HttpGet]
    public Location getLocation(int id)
    {
        int _id = id - 1;
        List<Location> loc = context.Locations.ToList();
        if (loc[_id] != null)
            return loc[_id];
        else
            return null;
    }

    [Route("game")]
    [HttpPost]
    public IActionResult postGame([FromBody] Game newGame)
    {
        newGame.GameID = context.Games.Count();
        context.Games.Add(newGame);

        return Created("", newGame);
    }

    [Route("game")]
    [HttpGet]
    public List<Game> getGames()
    {
        return context.Games.ToList();
    }

    [Route("game/{id}")]
    [HttpGet]
    public Game getGame(int id)
    {
        List<Game> game = context.Games.ToList();
        if (game[id] != null)
            return game[id];
        else
            return null;
    }
}

1 个答案:

答案 0 :(得分:2)

这是由于延迟加载,因此除非包含它们,否则不会加载存储在其他表中的对象。 Link

您可以使用Include("Question")来完成此操作,因此完整的语法为:

context.Locations.Include("Question"),因此您将在检索位置时包含问题

您还可以通过链接context.Locations.Include("Question").Include("SomethingElse")

来进行多个包含 我在您的代码getLocation中看到的

编辑仍然没有使用包含。参见下面的正确使用方法

public Location getLocation(int id)
{
    int _id = id - 1;
    List<Location> loc = context.Locations.Include("Question").ToList();
    if (loc[_id] != null)
        return loc[_id];
    else
        return null;
}

第二次修改 另外,我会重写getLocation,因为您首先获取整个位置后才拉整个列表

public Location getLocation(int id)
{
    int _id = id - 1;
    //FirstOrDefault will return automatically a null if the id cannot be found. 
    //This will result in only getting the single Location from context instead the complete list
    return context.Locations.Include("Question").FirstOrDefault(x=>x.id == _id);
}