反序列化JSON对象的属性仅在存储库类中始终为null

反序列化JSON对象的属性仅在存储库类中始终为null,json,asp.net-core-webapi,dbcontext,Json,Asp.net Core Webapi,Dbcontext,我的控制器中有一个简单的GET函数,可以从我的存储库返回一小部分对象。每个对象上的一个属性仅在repository类中始终为null,而在最初填充dbcontext时,它本身不为null。我只是在MemoryDatabase中使用了一个InMemoryDatabase 以下是my Home.cs模型课程: public class Home { public int Id { get; set; } [Required(ErrorMessage = "Address

我的控制器中有一个简单的
GET
函数,可以从我的存储库返回一小部分对象。每个对象上的一个属性仅在repository类中始终为null,而在最初填充dbcontext时,它本身不为null。我只是在MemoryDatabase中使用了一个
InMemoryDatabase

以下是my Home.cs模型课程:

public class Home
{
    public int Id { get; set; }

    [Required(ErrorMessage = "Address is required")]
    public Address Address { get; set; } // this is what is null

    [Required(ErrorMessage = "Number of rooms is required")]
    public int NumRooms { get; set; }

    [Range(1, 5, ErrorMessage = "Must give a rating between 1 and 5")]
    public int Rating { get; set; }
}
下面是Address.cs模型:

public class Address
{
    public int Id { get; set; }

    [Required(ErrorMessage = "City is required")]
    public string City { get; set; }

    [Required(ErrorMessage = "State is required")]
    public string State { get; set; }

    [Required(ErrorMessage = "ZipCode is required")]
    [StringLength(5, MinimumLength = 5)]
    public string ZipCode { get; set; }
}
这是我在
Program.cs
中的
Main
函数,我正在调用该函数生成一些数据:

public class Program
{
    public static void Main(string[] args)
    {
        var host = CreateHostBuilder(args).Build();
        using (var scope = host.Services.CreateScope())
        {
            var services = scope.ServiceProvider;
            var context = services.GetRequiredService<RepositoryContext>();

            DataGenerator.SeedData(context);
        }
        host.Run();
    }

    // rest of Program.cs
}
这是Homes.json的

[
  {
    "Address": {
      "City": "CityOne",
      "State": "MA",
      "ZipCode": "44444"
    },
    "NumRooms": "4",
    "Rating": "4"
  },
  {
    "Address": {
      "City": "CityTwo",
      "State": "MA",
      "ZipCode": "3333"
    },
    "NumRooms": "3",
    "Rating": "3"
  },
  {
    "Address": {
      "City": "AnotherCity",
      "State": "MA",
      "ZipCode": "22222"
    },
    "NumRooms": "2",
    "Rating": "2"
  },
  {
    "Address": {
      "City": "SomeCity",
      "State": "MA",
      "ZipCode": "11111"
    },
    "NumRooms": "1",
    "Rating": "1"
  }
]
下面是Dbcontext类:

public class RepositoryContext : DbContext
{
    public DbSet<Home> Homes{ get; set; }

    public RepositoryContext(DbContextOptions<RepositoryContext> options) : base(options)
    {
    }
}
HomeRepository
类:

public class DataGenerator
{
    public static void SeedData(RepositoryContext context)
    {
        if (!context.Homes.Any())
        {
            var homeData = System.IO.File.ReadAllText("Data/Homes.json");
            var homes = JsonConvert.DeserializeObject<List<Home>>(homeData);
            context.AddRange(homes);
            context.SaveChanges();
        } // I verify here that the home objects in context DO have valid Addresses
    }
}
public class HomeRepository : IHomeRepository
{
    private readonly RepositoryContext _context;

    public HomeRepository(RepositoryContext context)
    {
        _context = context; // context shows addresses as null here
    }

    public async Task<IEnumerable<Home>> GetHomes()
    {
        var homes = await _context.Homes.ToListAsync(); // address is null here for all home objects
        return homes;
    }
}
公共类HomeRepository:IHomeRepository
{
私有只读存储上下文\u上下文;
公共HomeRepository(RepositoryContext)
{
_context=context;//context在这里将地址显示为null
}
公共异步任务GetHomes()
{
var homes=await _context.homes.ToListAsync();//对于所有主对象,此处的地址为空
返回家园;
}
}
最后,这里是相关的控制器类:

[ApiController]
[Route("api/[controller]")]
public class HomeController : ControllerBase
{
    private readonly IHomeRepository _repository;

    public HomeController(IHomeRepository repository)
    {
        _repository = repository;
    }

    [HttpGet]
    public async Task<IActionResult> GetHomes()
    {
        var homes = await _repository.GetHomes(); // address is null here for all objects
        return Ok(homes);
    }
}
[ApiController]
[路由(“api/[控制器]”)]
公共类家庭控制器:ControllerBase
{
专用只读IHomeRepository存储库;
公共HomeController(IHomeRepository存储库)
{
_存储库=存储库;
}
[HttpGet]
公共异步任务GetHomes()
{
var homes=await _repository.GetHomes();//此处所有对象的地址均为空
返回Ok(家);
}
}

忘记包含
地址
实体。这就是为什么
地址
没有出现的原因。
添加
。包括(h=>h.address)
家庭

    public async Task<IEnumerable<Home>> GetHomes()
    {
        //var homes = await _context.Homes.ToListAsync(); // address is null here for all home objects
        
        var homes = await _context.Homes.Include(h=>h.Address).ToListAsync(); // include address table

        return homes;
    }
公共异步任务GetHomes() { //var homes=await _context.homes.ToListAsync();//对于所有主对象,此处的地址为空 var homes=wait _context.homes.Include(h=>h.Address).ToListAsync();//Include地址表 返回家园; }
截图

它起作用了


顺便说一句,这是我见过的最详细的问题非常感谢你!它工作得很好。当模型已经在另一个模型中时,我没有意识到您必须使用
。Include
。因此,如果我在另一个模型类中有多个模型类,我就必须将
调用链接在一起。包括
调用?我不想听起来不领情,但在我看来,这个问题太详细了。这看起来不像是一个好主意me@pfinferno是的,您可以链接多个包含项。请看这里:
    public async Task<IEnumerable<Home>> GetHomes()
    {
        //var homes = await _context.Homes.ToListAsync(); // address is null here for all home objects
        
        var homes = await _context.Homes.Include(h=>h.Address).ToListAsync(); // include address table

        return homes;
    }