【发布时间】:2019-05-16 03:49:32
【问题描述】:
如果您能在这方面帮助我,我们将不胜感激。
这是简化的示例:
型号:人
public int Id { get; set; }
public string Fname { get; set; }
public string Lname { get; set; }
public ICollection<TbContact> TbContact { get; set; }
型号:联系方式
public int Id { get; set; }
public string Phone { get; set; }
public string Email { get; set; }
public int PersonId { get; set; }
public TbPerson Person { get; set; }
数据库上下文:
public virtual DbSet<Blog> Blog { get; set; }
public virtual DbSet<Post> Post { get; set; }
modelBuilder.Entity<TbContact>(entity =>
{
entity.Property(e => e.Email).HasMaxLength(50);
entity.Property(e => e.PersonId).HasColumnName("Person_Id");
entity.Property(e => e.Phone).HasMaxLength(50);
entity.HasOne(d => d.Person)
.WithMany(p => p.TbContact)
.HasForeignKey(d => d.PersonId)
.HasConstraintName("FK_TbContact_TbPerson");
});
modelBuilder.Entity<TbPerson>(entity =>
{
entity.Property(e => e.Fname).HasMaxLength(50);
entity.Property(e => e.Lname).HasMaxLength(50);
});
全部由 Scaffold-DbContext 命令生成。 这是 Api 控制器:
private readonly ApiContext _context;
public PersonsController(ApiContext context)
{
_context = context;
}
// GET: api/TbPersons
[HttpGet]
public async Task<IActionResult> GetPerson()
{
var person = await _context.TbPerson.Include(x => x.TbContact).ToListAsync();
return Ok(person);
}
并且它返回 NULL 而没有编译器错误, 但如果我像下面这样删除“.include”:
public async Task<IActionResult> GetPerson()
{
var person = await _context.TbPerson.ToListAsync();
return Ok(person);
}
结果是:
[{"id":1,"fname":"Josh","lname":"R","tbContact":[]}
正如我提到的,我需要获得“tbperson”,包括“tbcontact”。
【问题讨论】:
-
我尝试升级到 .Net core 2.2,EF Core 2.2 与上面的代码相同,结果从 null 更改为:"[{"id":1,"phone":"xxxxxxx" ,"email":"xxxx@xxx.com","personId":1,"person":{"id":1,"fname":"Josh","lname":"R","tbContact": [ "有什么建议吗???
标签: entity-framework entity-framework-core ef-core-2.1 db-first