I'm unsuccessfully reading and fighting with the idea how to properly build a simple MVC web application. There are many tutorials but each one sucks, I mean they show how to add simple type fields to ApplicationUser
and use them in AccountViewModel
and ManageViewModel
. What I need is using custom objects, not simple fields.
I made a simple solution for testing. I try to implement One-to-one (UserProfile - Address) relationship.
Here is my ApplicationUser.cs class:
namespace DBRelationsTesting.Models
{
// Add profile data for application users by adding properties to the ApplicationUser class
public class ApplicationUser : IdentityUser
{
public string FirstName { get; set; }
public string LastName { get; set; }
public virtual AddressViewModel Address { get; set; }
public virtual ICollection<PhotoGalleryViewModel> PhotoGallery { get; set; }
}
}
AddresViewModel class:
namespace DBRelationsTesting.Models.AccountViewModels
{
public class AddressViewModel
{
[Key]
public int AddressId { get; set; }
public string City { get; set; }
public string Country { get; set; }
}
}
Consequently I created the database class AddressViewModel
, updated the Views, added DbSets
and modified the Controllers.
All I got was that the database is being filled with foreign key data but I can't get the foreign key fields to be displayed in Views. From what I read this is some safety limitation of User Authentication. Is it true?
In a separate testing project I tried making the same but not in the User Authentication classes and after using the Include()
function in the Controller It works(on the example of Details action). It fills the foreign class fields.
// GET: UserProfiles/Details/5
public async Task<IActionResult> Details(int? id)
{
if (id == null)
{
return NotFound();
}
var userProfile = await _context.UserProfile
.Include(usrProfile => usrProfile.Address)
.SingleOrDefaultAsync(m => m.UserProfileID == id);
if (userProfile == null)
{
return NotFound();
}
return View(userProfile);
}
Why in ManageController
(in the project with Authentication) can't I use Include()
?
In this case how can I link my custom classes with the User Authentication system so that the logged in user won't see other users data?
Should I add the built-in User object in my custom UserProfile
class like below? Will it work?
public virtual User User { get; set; }