I have a question regarding foreign keys in EF Core.
Let’s say I have this class:
public class User
{
public int UserID { get; set; } // PK
}
public class Workout
{
public int WorkoutID { get; set; } // PK
public int UserID { get; set; } // FK, the userid that created this workout
}
This feels enough to me. Because if you need to get the user who created workout X, you can do it in one line with LINQ in some service/repo created by you.
I’ve tried learning about foreign keys in EF Core and in every example I see it looks like this:
public class Workout
{
public int WorkoutID { get; set; } // PK
public int UserID { get; set; }
[ForeignKey("UserID")]
public User User { get; set; } // navigation property
}
What does this do exactly and how is it better? It feels bad to me to hold one more field in the model when you can just hold the ID.
What’s the difference?
I’m still new to databases, have some empathy. Thanks!
2
Benefits of Navigation Properties
-
Simplified queries: with navigation properties, you can easily load related entities. For example:
var workouts = context.Workouts.Include(w => w.User).ToList();
This will load all workouts along with their corresponding users in a single query.
-
Eager loading: navigation properties enable you to use eager loading with the Include method, which is useful for optimizing database access by fetching related data in a single query.
-
Better code readability: accessing related entities directly improves code readability. Instead of having to perform a join manually, you can do something like:
var user = workout.User;
-
Change tracking: EF Core is built to work well with navigation properties, making it easier to manage related entity states. When you modify the User property on a Workout, EF can track changes more efficiently.
-
Relationship definitions: by defining navigation properties, you also make your data model more expressive. It clearly indicates the relationships between entities, which can be helpful for anyone else (or yourself in the future) reading the code.
2