Entity framework 2.1 , 2.2 : Loading related data returns Null or Incomplete

db-first ef-core-2.1 entity-framework entity-framework-core

Question

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".

1
1
12/16/2018 7:42:11 PM

Popular Answer

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; 
}); 
}
0
12/15/2018 2:03:17 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow