C
C#4mo ago
G1lles

Entity Framework Foreign Key

What is better? Declaring your foreign keys in your model and declaring it in your modelbuilder (.hasForeignKey) or doing it by only declaring the relationship in your modelbuilder?
No description
3 Replies
boiled goose
boiled goose4mo ago
i believe modelbuilder is what would conventionally be suggested
Keswiik
Keswiik4mo ago
There is also a ForeignKey attribute that you can use Means you don't need to configure it in your dbcontext at all
Angius
Angius4mo ago
Personally, I use FKs and nav properties in my models
public class Blogpost
{
public int Id { get; set; }
public required string Title { get; set; }
public User Author { get; set; }
public int AuthorId { get; set; }
}
public class Blogpost
{
public int Id { get; set; }
public required string Title { get; set; }
public User Author { get; set; }
public int AuthorId { get; set; }
}
This way I can always construct a Blogpost with a related Author without having to fetch the author first And since it just works by convention, there's no configuration needed Be it with attributes or modelbuilder
Want results from more Discord servers?
Add your server
More Posts