1

It would really appreciated if you would help me on this.

here is the simplified sample :

Model:Person

public int Id { get; set; }
public string Fname { get; set; }
public string Lname { get; set; }

public ICollection<TbContact> TbContact { get; set; }

Model:Contact

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

DB Context:

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

All generated by Scaffold-DbContext command. Here is Api Controller :

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

And its return NULL with no compiler error, but if i remove the ".include" like below :

public async Task<IActionResult> GetPerson()
{
var person = await _context.TbPerson.ToListAsync();
return Ok(person);
}

The result would be :

[{"id":1,"fname":"Josh","lname":"R","tbContact":[]}

As i mentioned i need to get "tbperson" including "tbcontact".

Josh
  • 559
  • 5
  • 8
  • I tried to upgrade to .Net core 2.2 , EF Core 2.2 with same code as above the result has changed from null to : "[{"id":1,"phone":"xxxxxxx","email":"xxxx@xxx.com","personId":1,"person":{"id":1,"fname":"Josh","lname":"R","tbContact":[ " Is there any suggestion ??? – Josh Dec 15 '18 at 00:50

1 Answers1

0

Apparently this happens because of self-reference loops in JSON so we can set this off by code below and it resolve the issue:

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; 
}); 
}
Josh
  • 559
  • 5
  • 8