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);
user.Estates.Add(estate);
However when I type it like that, it saves data correctly in db:
var user = await _userManager.GetUserAsync(User);
estate.User = user;
context.Add(estate);
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)
{
base.OnModelCreating(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
{
[Key]
public int Id { get; set; }
[MaxLength(100)]
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:
migrationBuilder.CreateTable(
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);
table.ForeignKey(
name: "FK_Estates_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateTable(
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);
});
There are different ways to get related data of a model.
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:
UserManager<User> _userManager
.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)
.FirstOrDefaultAsync(YOUR_CONDITION);