Search code examples
c#entity-framework-6foreign-key-relationship

Foreign-Key References to the Same Entity


I have the below model:

class Client
{        
    [Key]
    public int Id { get; set; }
    public string Nom { get; set; }
    public string Prenom { get; set; }         
    public Nullable<DateTime> date_naissance { get; set; }
    public Sex? Sexe { get; set; }
    public Client Parent { get; set; }
}

I used code first to generate my table. When I tried to save the records using the code below, I wasn't able to determine how to populate the Parent field. A Client can be a parent of other Clients.

Client client = new Client();

client.Id = int.Parse(item.ID);
client.Nom = item.Nom;
client.Prenom = item.Prenom;
client.date_naissance = DateTime.Parse(item.DateNaissance);
client.Sexe = (Sex)Enum.Parse(typeof(Sex), item.Sexe);

int parent;
bool par = int.TryParse(item.Parent, out parent);

// this does not work:                       
if (par)
    client.Parent.Id = parent;

db.clients.Add(client);
db.SaveChanges();

Solution

  • Try making the navigation properties (i.e. Parent) virtual and don't forget to initialize them. So first you have to change your class property to:

    public virtual Client Parent { get; set; }
    

    and then in the code:

    client.Parent = new Parent();
    client.Parent.Id = parentId;