I am trying to get the whole graph of an entity User
. The User
class is:
Updated
public class User
{
[Key]
public int Id { get; set; }
public string email_address { get; set; }
[Column("Password Hash")]
public string PasswordHash { get; set; }
public string custnmbr { get; set; }
public Customer Customer { get; set; }
}
My Customer
Class:
public class Customer
{
[Key]
public string Custnmbr { get; set; }
public string Custname { get; set; }
public ICollection<User> Users { get; set; }
}
I have this in my DbContext:
public class EntityContext : DbContext
{
public EntityContext(DbContextOptions<EntityContext> options)
: base(options)
{
}
public DbSet<User> Users { get; set; }
public DbSet<Customer> Customers { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<User>()
.HasOne<Customer>(u => u.Customer)
.WithMany(c => c.Users)
.HasForeignKey(u => u.custnmbr);
}
}
My UserService:
public class UserService : IUserService
{
private readonly EntityContext _context;
public UserService(EntityContext context)
{
_context = context;
_context.Users.Include("Customer").Load();
}
public IEnumerable<User> GetAll()
{
var users = _context.Users.Local.ToList();
return users;
}
public User GetByUsername(string emailAddress)
{
var user = _context.Users.Local.SingleOrDefault(x => x.email_address == emailAddress);
return user;
}
}
My UserControler:
[Route("api/Users")]
[ApiController]
public class UsersController : ControllerBase
{
private readonly IUserService _userService;
public UsersController(IUserService userService)
{
_userService = userService;
}
[HttpGet("GetAll")]
public IActionResult GetAll()
{
var users = _userService.GetAll();
return Ok(users);
}
[HttpGet("GetUser")]
public IActionResult GetUser(string emailAddress)
{
var user = _userService.GetByUsername(emailAddress);
return Ok(user);
}
}
And GetAll() returns the whole graph for all Users
. But GetUser() returns a single User
with property Customer
null.
How can I get the whole User
graph including the property Customer
?
Any help would be appreciated.
Microsoft Visual Studio Community 2019 - Version 16.10.3
Microsoft.AspNetCore (5.0.0)
Microsoft.EntityFrameworkCore (5.0.7)