实体框架2.1、2.2:加载相关数据返回Null或Incomplete

时间:2018-12-14 21:27:09

标签: entity-framework entity-framework-core ef-core-2.1 db-first

如果您能帮助我,我将不胜感激。

这是简化的示例:

型号:人

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":[]}

正如我提到的,我需要获得包括“ tbcontact”在内的“ tbperson”。

1 个答案:

答案 0 :(得分:0)

显然,这是由于JSON中的自引用循环导致的,所以我们可以通过下面的代码对此进行设置,并解决此问题:

public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApiContext>(options =>     
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))
.UseLazyLoadingProxies());

services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
.AddJsonOptions(options => {
options.SerializerSettings.ReferenceLoopHandling=ReferenceLoopHandling.Ignore; 
}); 
}