.NET MVC Core 2.2 - Can't access user related entity (foreign key)

.net-core asp.net-core asp.net-identity c# entity-framework-core


I am writting my first own app in MVC Core 2 and I am having trouble accessing Estate Entity which have foreign key to User. I have check my db, Estate record is storing userId correctly:

When I try to get context.Estates.FirstOrDefault(m => m.Id == id); I get an Estate entity, but with User == null:

When I try to access it via :

var user = await _userManager.GetUserAsync(User);
var estate = user.Estates.FirstOrDefault(m => m.Id == id);

I get null exception on Estates list. Also trying to save it this way gives me an exception:

var user = await _userManager.GetUserAsync(User);

However when I type it like that, it saves data correctly in db:

var user = await _userManager.GetUserAsync(User);
estate.User = user;

I have no clue what I did wrong here. I provide my code below, I hope you can give me some tips/advices.

Thats how i build context based on IdentityDbContext:

public class ReaContext : IdentityDbContext<User>
    public DbSet<Estate> Estates { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        optionsBuilder.UseNpgsql("Server=localhost;Port=5432;Database=rea-dev;User Id=postgres;Password=admin;");

    public ReaContext(DbContextOptions<ReaContext> options)
        : base(options)
    { }

    public ReaContext()
        : base()
    { }

My User model:

public class User : IdentityUser
    public List<Estate> Estates { get; set; }

Estate model:

public class Estate
    public int Id { get; set; }
    public string City { get; set; }

    public User User { get; set; }

And thats how I add services:

services.AddDbContext<ReaContext>(options => options.UseNpgsql("Server=localhost;Port=5432;Database=rea-dev;User Id=postgres;Password=admin;"));

services.AddIdentity<User, IdentityRole>().AddEntityFrameworkStores<ReaContext>();

I also provide Fluent Api migrations:

        name: "Estates",
        columns: table => new
            Id = table.Column<int>(nullable: false)
                .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.SerialColumn),
            CreationDate = table.Column<DateTime>(nullable: false),
            UpdateDate = table.Column<DateTime>(nullable: false),
            ExpirationDate = table.Column<DateTime>(nullable: false),
            City = table.Column<string>(maxLength: 100, nullable: true),
            UserId = table.Column<string>(nullable: true)
        constraints: table =>
            table.PrimaryKey("PK_Estates", x => x.Id);
                name: "FK_Estates_AspNetUsers_UserId",
                column: x => x.UserId,
                principalTable: "AspNetUsers",
                principalColumn: "Id",
                onDelete: ReferentialAction.Restrict);

        name: "AspNetUsers",
        columns: table => new
            Id = table.Column<string>(nullable: false),
            UserName = table.Column<string>(maxLength: 256, nullable: true),
            NormalizedUserName = table.Column<string>(maxLength: 256, nullable: true),
            Email = table.Column<string>(maxLength: 256, nullable: true),
            NormalizedEmail = table.Column<string>(maxLength: 256, nullable: true),
            EmailConfirmed = table.Column<bool>(nullable: false),
            PasswordHash = table.Column<string>(nullable: true),
            SecurityStamp = table.Column<string>(nullable: true),
            ConcurrencyStamp = table.Column<string>(nullable: true),
            PhoneNumber = table.Column<string>(nullable: true),
            PhoneNumberConfirmed = table.Column<bool>(nullable: false),
            TwoFactorEnabled = table.Column<bool>(nullable: false),
            LockoutEnd = table.Column<DateTimeOffset>(nullable: true),
            LockoutEnabled = table.Column<bool>(nullable: false),
            AccessFailedCount = table.Column<int>(nullable: false)
        constraints: table =>
            table.PrimaryKey("PK_AspNetUsers", x => x.Id);
12/30/2018 1:39:25 PM

Accepted Answer

There are different ways to get related data of a model.

  1. Eager loading: means that the related data is loaded from the database as part of the initial query.
  2. Explicit loading: means that the related data is explicitly loaded from the database at a later time.
  3. Lazy loading: means that the related data is transparently loaded from the database when the navigation property is accessed.

So in your case you can use Eager loading by doing the following:

context.Estates.Include(e => e.User).FirstOrDefault(m => m.Id == id);

For more information read this: Loading Related Data.

Edit: an example for achieving Eager loading pattern on the IdentityUser:

You can achieve this by either:

  1. Injecting UserManager<User> _userManager.
  2. Creating your own Service as in Service/Repository Design Pattern.

Let's say you picked the first option. Then you can do the following:

var user = await _userManager.Users
                 .Include(u => u.Estates)
12/30/2018 3:32:30 PM

Related Questions


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