Anton Minchenko
Anton Minchenko

Reputation: 461

Why Entity Framework doesn't initialize field?

I created two entities, added them to the data context, created a relationship between them, performed the migration. After registering the user, the application created his record in the database and established a connection with the default image. During the next request - ProfilePictureId is initialized by the correct value, but ProfilePicture is null.

User.cs

public class User: IdentityUser
{
    public int? ProfilePictureId { get; set; }
    public virtual Image ProfilePicture { get; set; }
}

Image.cs

public class Image
{
    public int Id { get; set; }
    public string Filename { get; set; }
}

RegisterModel.cshtml.cs

[AllowAnonymous]
public class RegisterModel : PageModel
{
    private readonly SignInManager<User> _signInManager;
    private readonly UserManager<User> _userManager;
    private readonly UserSettings _userSettings;
    private readonly ApplicationDbContext _dbContext;
    private readonly ILogger<RegisterModel> _logger;
    private readonly IEmailSender _emailSender;

    public RegisterModel(
        UserManager<User> userManager,
        SignInManager<User> signInManager,
        IOptions<UserSettings> userSettings,
        ApplicationDbContext dbContext,
        ILogger<RegisterModel> logger,
        IEmailSender emailSender)
    {
        _userManager = userManager;
        _signInManager = signInManager;
        _userSettings = userSettings.Value;
        _dbContext = dbContext;
        _logger = logger;
        _emailSender = emailSender;
    }

    // ...

    public async Task<IActionResult> OnPostAsync(string returnUrl = null)
    {
        // ...

        if (ModelState.IsValid)
        {
            // var user = new User ...

            SetUserDefaultParams(user);

            var result = await _userManager.CreateAsync(user, Input.Password);

            if (result.Succeeded)
            {
                // ...
            }
            foreach (var error in result.Errors)
            {
                ModelState.AddModelError(string.Empty, error.Description);
            }
        }

        // If we got this far, something failed, redisplay form
        return Page();
    }

    private void SetUserDefaultParams(User user)
    {
        // ...
        if (_userSettings != null)
        {
            var image = _dbContext.Images
                .Where(
                i => i.Filename == _userSettings.DefaultProfilePicture)
                .FirstOrDefault();
            user.ProfilePicture = image; // this always returns the desired value (not null)
        }
        _userManager.UpdateAsync(user).Wait();
    }
}

I expect ProfilePicture to be not null in _LoginPartial.cshtml Razor-page:

@inject UserManager<User> UserManager
@{
    var user = UserManager.GetUserAsync(User).Result;
    var pathToProfilePicture = string.Empty;

    if (user != null)
    {
        pathToProfilePicture = 
            $"../../Resources/Images/{user.ProfilePicture.Filename}"; // here 
// I get NullReferenceException
    }
}

Upvotes: 0

Views: 158

Answers (1)

Jelle Schr&#228;der
Jelle Schr&#228;der

Reputation: 344

Try adding .Include(e => e.ProfilePicture) in your statement. https://learn.microsoft.com/en-us/ef/ef6/querying/related-data

Upvotes: 2

Related Questions