Ryan Kohn
Ryan Kohn

Reputation: 13509

When to store just the ID in a class vs storing a fully-populated object?

Let's say I have two tables as below:

FoodType:

ID | Name       |  ... additional fields ...
---------------------------------------------
1  | Fruit      | ...
2  | Vegetable  | ...
Food:

ID | FoodTypeId | Name
----------------------
1  | 1          | Apple
2  | 1          | Orange
3  | 2          | Carrot
4  | 2          | Spinach
5  | 1          | Pear

When I'm structuring a class for Food, in what cases would it be better to define just FoodTypeId instead of a whole FoodType object?

i.e.

public class Food
{
    public int Id {get; set;}
    public int FoodTypeId {get; set;}
    public string Name {get; set;}
}

vs

public class Food
{
    public int Id {get; set;}
    public FoodType FoodType {get; set;}
    public string Name {get; set;}
}

public class FoodType
{
    public int Id {get; set;}
    public string Name {get; set;}
}

Upvotes: 0

Views: 662

Answers (1)

Servy
Servy

Reputation: 203834

It would be better to just store the ID if you infrequently need to use the other information about the FoodType object, and fetching and populating that information takes a noticeable amount of effort.

You would want to store an actual food type object if you frequently use the additional information or the effort to populate it is sufficiently small.

There are of course other hybrid situations, such as the object having both an ID and an actual object, but having the actual object be 'null' instead of populated in certain situations, or to have an actual object that only populates certain fields in the referenced object. Even more sophisticated options will have the actual object, rather than an id, but populate it lazily or eagerly based on its usage.

Upvotes: 3

Related Questions