David Houthoofdt
David Houthoofdt

Reputation: 19

Best way of getting related entity objects

I have 2 tables :

Table 1 called type has an id and a name
Table 2 called subtype has an id, a name and a typeId

TypeId is a reference to table 1 and a foreign key is created.

My objects :

public class BType
{
    [HiddenInput(DisplayValue = false)]
    [Key]
    public int Id { get; set; }
    [Required(ErrorMessage = "Naam is verplicht")]
    public string Naam { get; set; }
}

and

public class SubType
{
    [HiddenInput(DisplayValue = false)]
    [Key]
    public int Id { get; set; }
    [Required(ErrorMessage = "Naam is verplicht")]
    public string Naam { get; set; }
    [Required(ErrorMessage = "Type is verplicht")]
    public int TypeID { get; set; }

    private BType _Type = null;

    public BType Type
    {
        get {
            if (this._Type == null)
            {
                BTypeContext repo = new BTypeContext();
                this._Type = repo.BTypes.Where(x => x.Id == this.TypeID).FirstOrDefault();
            }
            return this._Type;
        }
    }

}

I'm not convinced that the way that i'm loading the type in subtype is the correct way.

In the view i need to create a table for the subtypes but i also need the information for the type for that subtype.

What's the best way to get the type info inside the subtype?

Upvotes: 0

Views: 51

Answers (1)

SWilko
SWilko

Reputation: 3612

You can make your related Type virtual so that EF lazily loads related data I've added ForeignKey attribute for clarity

public class SubType
{
  [HiddenInput(DisplayValue = false)]
  [Key]
  public int Id { get; set; }

  [Required(ErrorMessage = "Naam is verplicht")]
  public string Naam { get; set; }

  [Required(ErrorMessage = "Type is verplicht")]
  public int TypeID { get; set; }

  [ForeignKey("TypeID")]
  public virtual BType Type { get; set; }
}

Upvotes: 1

Related Questions