I have a Database Schema like this.
I am working on gettingDetailByPostID API which needs to return 1 Object as follows.
Guid PostId;
Guid UserId;
String? Username;
String? MediaPath;
int Likes; // count the number of likes of the post
String? Caption;
bool IsLiked;
IEnumerable<Comment>? Comments; // List of comments in the post
I am having difficulty in joining the tables together to get more data from the User and Comment tables. How can I do this with ef core 6.
2
Answers
firsr have a
DbSet
property for in your db context inherited class which may look like thispublic DbSet<Post> Posts { get; set; }
.then inject the dbcontext to your required service as constructor injection.
the you can do
var post = yourDbContenxt.Posts.FirstOrDefaultAsync(p=>p.PostId==yourPostId);
The best way to do this would be in a single transaction.
I believe you already have configured EF with navigation and you should have an entities like this
If not, you should have a look on the microsoft documentation or on this great tutorial site
If it is configured with navigation (but without lazy loading to avoid infinite loop, and to have an ecological use of your server ressources 🙂 )
Then you can build your object within the same context instanciation such as this short exemple
I hope it helps !