C
C#•2mo ago
N_58

Should I use navigation properties in EF Core?

When using EF Core should I always use navigation properties or never? for example I have:
class Post
{
public string Content { get; set; }
public string AuthorId { get; set; }
public User Author { get; set; } // Should I use it?
}
class Post
{
public string Content { get; set; }
public string AuthorId { get; set; }
public User Author { get; set; } // Should I use it?
}
class User
{
public string Name { get; set; }
public ICollection<Post> Posts { get; set; } // Should I use it?
}
class User
{
public string Name { get; set; }
public ICollection<Post> Posts { get; set; } // Should I use it?
}
I use .NET 9 in my smaller project and I wonder if it's better to use it or not in terms of performance?
14 Replies
Jimmacle
Jimmacle•2mo ago
navigation properties are a major part of EF, if your entities have a relationship you conventionally model it by defining navigation properties
N_58
N_58OP•2mo ago
but as i've seen there's an option to omit them
Jimmacle
Jimmacle•2mo ago
yes, you don't have to use them
N_58
N_58OP•2mo ago
and I just wondered if it's good idea, better or what
Keswiik
Keswiik•2mo ago
You can have both, which is what I do.
Jimmacle
Jimmacle•2mo ago
it's much more convenient to use navigation properties in a query than writing explicit joins
N_58
N_58OP•2mo ago
and should i use virtual aswell?
Jimmacle
Jimmacle•2mo ago
no performance differences to mention that i'm aware of
N_58
N_58OP•2mo ago
it uses lazy loading then, right?
Jimmacle
Jimmacle•2mo ago
no, that's related to lazy loading which you should never use
N_58
N_58OP•2mo ago
oh, why not? 🤔
Jimmacle
Jimmacle•2mo ago
because it causes surprise synchronous IO when you're accessing properties of what looks like a normal C# object ideally you use a .Select in your query to project out just the data you actually want, all in one go
N_58
N_58OP•2mo ago
alright, thanks i guess 😅 that explains a bit
Keswiik
Keswiik•2mo ago
public class SomeEntity {
public int Id { get; set; }

public int? NavPropertyId { get; set; }
public SomeOtherEntity? NavProperty { get; set; }
}
public class SomeEntity {
public int Id { get; set; }

public int? NavPropertyId { get; set; }
public SomeOtherEntity? NavProperty { get; set; }
}
^ this is also valid in EF, gives you the ability to reference nav properties in your queries, but also explicitly use the relational columns if you want to

Did you find this page helpful?