Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

ASP.NET MVC Core foreign key

I have a database first asp.net mvc core project and I’m not sure how to work with foreign keys.

[Table("tbUser")]
public class User
{
    [Key]
    [Column("UserID")]
    public int UserID { get; set; }

    [Column("RoleID")]
    public int RoleID { get; set; }

    [ForeignKey("RoleID")]
    public Role Role { get; set; }
}

[Table("tbRole")]
public class Role
{
    [Key]
    [Column("RoleID")]
    public int RoleID { get; set; }

    [Column("Role")]
    public string RoleName { get; set; }

    public ICollection<User> Users { get; set; }
}

All the properties load from my database but the Role Role in User stays null

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Try adding .Include(u => u.Role) when loading from database. This works like SQL JOIN.

https://www.entityframeworktutorial.net/efcore/querying-in-ef-core.aspx

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading