【问题标题】:ASP.NET json object doesn't contain custom objectASP.NET json 对象不包含自定义对象
【发布时间】:2019-03-31 06:09:07
【问题描述】:

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

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

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;
    }
}

【问题讨论】:

  • “但是,当我检索位置时,问题参数始终为空”- 检索位置的代码在哪里?目前这不是问题。请edit提出问题。
  • 是否正确存储问题表中的问题?如果您的延迟加载可能被禁用,您必须在查询中明确包含问题...如果您发布检索查询将更容易帮助:D
  • 我刚刚添加了控制器类。

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


【解决方案1】:

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

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

context.Locations.Include("Question") 所以你会在检索位置时包含问题

您还可以通过链接context.Locations.Include("Question").Include("SomethingElse") 来执行多个包含

Edit 正如我在您的代码中看到的 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);
}

【讨论】:

  • 我似乎无法找到应该调用“.Include()”方法的地方。我在帖子末尾添加了我的控制器类。
  • 已修复。我无法使用“.Include()”,因为它没有在控制器类的顶部自动包含“using Microsoft.EntityFrameworkCore”。
  • @MyNameIsGuzse 我编辑了,我看到你仍然没有在正确的位置使用包含
  • @MyNameIsGuzse 也看看第二次编辑,因为它是一种更简洁的方法,不会继续从上下文中提取所有数据而不是你需要的单个对象
  • 一切正常,标记为正确答案。非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-23
  • 2013-08-27
  • 2013-10-22
  • 2020-05-16
  • 1970-01-01
相关资源
最近更新 更多