0

I am trying to assign foreign keys to multiple models that I am working with and can't seem to figure out the proper way of doing this.

For this example, all classes are in the Models namespace.

Model-A.cs

public class ModelA {
    [Key]
    [Required]
    [Display(Name = "ID-FROM-A")]
    public int id { get; set; }
    
    public string name { get; set; }
    
    public string connection { get; set; }

    ...
}

Model-B.cs

public class ModelA {
    [Key]
    [Required]
    [Display(Name = "ID-FROM-B")]
    public int id { get; set; }
    
    public string name { get; set; }
    
    [Required]
    [ForeignKey("ID-FROM-A")] <--- ??? 
    public int idFromA { get; set; }

    ...
}

Model-C.cs

public class ModelA {
    [Key]
    [Required]
    [Display(Name = "ID-FROM-C")]
    public int id { get; set; }
    
    public string name { get; set; }
    
    [Required]
    [ForeignKey("ID-FROM-B")] <--- ??? 
    public int idFromB { get; set; }

    ...
}

As for the database:

MODELA                     MODELB                    MODELC
______                     ______                    ______
id (key)   <- 1 --|        id (key)  <- 1 --|        id (key)
name              |-- M -> model_A_Id       |-- M -> model_B_Id
connection                 ...                       ...
...

ModelA to ModelB is a one-to-many and ModelB to ModelC is a one-to-many.

I know there has to be a way to connect these models with foreign keys, in C#, but I am just not connecting the dots here. Any help is appreciated.

1 Answers1

0

You can specify navigation properties. For example, where ModelB has a foreign key for ModelA with 1 to many relationship, you can add a collection of ModelB to Model A like this:

public class ModelA {
    [Key]
    [Required]
    [Display(Name = "ID-FROM-A")]
    public int id { get; set; }
    
    public string name { get; set; }
    
    public string connection { get; set; }

    public virtual ICollection<ModelB> ModelBs { get; set; }

    ...
}

The use of 'virtual' for it means that it can support lazy loading and more efficient change tracking What effect(s) can the virtual keyword have in Entity Framework 4.1 POCO Code First?

Peter Dongan
  • 1,762
  • 12
  • 17