C#C
C#3y ago
Dropps

❔ efcore querying

hello there iam right now digging a bit deeper into ef core and how to query data correctly but i dont get my head around something maybe someone can help

i have following data classes:

namespace ExampleApp.Tests.Application.Models;

public class Product
{
    /// <summary>
    /// Unique identifier for the Product.
    /// </summary>
    public Guid Id { get; set; }
    
    /// <summary>
    /// Name of the Product.
    /// </summary>
    public string Name { get; set; } = string.Empty;
    
    /// <summary>
    /// Description of the Product.
    /// </summary>
    public string? Description { get; set; }
    
    /// <summary>
    /// Price of the Product.
    /// </summary>
    public decimal Price { get; set; }
    
    /// <summary>
    /// Average rating of the Product.
    /// </summary>
    public float? Rating { get; set; }
    
    /// <summary>
    /// Rating of the Product by the user.
    /// </summary>
    public int? UserRating { get; set; }
}

namespace ExampleApp.Tests.Application.Models;

public class ProductRating
{
    /// <summary>
    /// Unique identifier for the Product.
    /// </summary>
    public required Guid ProductId { get; init; }
    
    /// <summary>
    /// Unique identifier for the user.
    /// </summary>
    public required Guid UserId { get; init; }
    
    /// <summary>
    /// Rating of the Product by the user. 1-5.
    /// </summary>
    public required int Rating { get; init; }
    
    /// <summary>
    /// Comment on the Product by the user.
    /// </summary>
    public required string? Comment { get; init; }
}


i have a table for both of these classes now my question is how do i handle following behaviour:

GetAllAsync(Guid? userId)
GetByIdAsync(Guid productId, Guid? userId)

goal is to include the rating the user gove if the userid isnt null if it is then return just the product model but i dont get around how to do it

this is what i tried
        public async Task<Product?> GetByIdAsync(Guid id, Guid? userId = null, CancellationToken token = default)
        {
            if (userId == null)
            {
                return await _dbContext.Products.FindAsync(new object?[] { id }, cancellationToken: token);
            }

            return await _dbContext.Products
                .Include(f => f.Rating)
                .FirstOrDefaultAsync(f => f.Id == id, cancellationToken: token);
        }
Was this page helpful?