Foreign key with Entity Framework

advertisements

I have two model classes User and Reclamation, the Reclamation class have a foreign key for a User object, here are my two classes :

public class User
{
    [Key, ScaffoldColumn(false), Display(Name = "ID User")]
    public int idUser { set; get; }

    [Required, StringLength(16), Display(Name = "Login")]
    public string login { set; get; }

    [Required, StringLength(16), Display(Name = "Password")]
    public string password { set; get; }
}

public class Reclamation
{
    [Key, ScaffoldColumn(false), Display(Name = "ID Reclamation")]
    public int idReclamation { set; get; }

    [ForeignKey("idUser")]
    public User user{ set; get; }

    [Required, Display(Name = "ID Rapporteur")]
    public int idUser { set; get; }

    [Required, StringLength(30), Display(Name = "Message")]
    public string message{ set; get; }
}

Lets say for example that i have a user with an idUser=1. When i create a new Reclamation with idUser=1 it will be inserted fine in the database but my problem with the User object it doesn't contains the informations of the user with the idUser=1, should i code that manually in the set Property of the idUser attribute on the Reclamation class or i'm missing something ?


You can add a virtual property to your entity class to enable Lazy Loading. This way you you will enable EF to load the related object when it is requested.

        public class User
        {
            [Key, ScaffoldColumn(false), Display(Name = "ID User")]
            public int idUser { set; get; }

            [Required, StringLength(16), Display(Name = "Login")]
            public string login { set; get; }

            [Required, StringLength(16), Display(Name = "Password")]
            public string password { set; get; }

            public virtual Reclamation Reclamation {get; set;}

            /*if you have one to many relationship, use Collection<T>
   and initialize it in the constructor Reclamations = new Collection<Reclamation>();*/
            public virtual Collection<Reclamation> Reclamations {get; set;}
        }

Your other option is to use Eager Loading, as mentioned above. Something like:

context.Users.Include(x => x.Reclamations).ToList();