0

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 ?

Erik Philips
  • 53,428
  • 11
  • 128
  • 150
user3578325
  • 239
  • 2
  • 6
  • 12

2 Answers2

2

you should try this code:

UserData.Include("Reclamation").ToList();
2

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();
vortex
  • 1,048
  • 1
  • 10
  • 17
  • it worked fine thanks, but can you explain for me why it didn't worked without the virtual property ? what is the role of virtual here ? – user3578325 Mar 18 '15 at 12:35
  • It`s a rule/convention/ in Entity Framework, which enables Lazy Loading. The answer here http://stackoverflow.com/questions/7738722/entity-framework-4-1-virtual-properties has detailed explanation. – vortex Mar 18 '15 at 12:44