Entity Framework: How to get the list of attribute codes for each item?
09:32 01 Dec 2025

I am writing WebAPI endpoint, data from SQL server, EF Core 8.0.

Having the table of products and the table that maps the product codes to product attributes (one to many) with models:

public class Product
{
   public string Code { get; set; }
   public string Name { get; set; }
   public decimal CatalogPrice { get; set; }
}

public class ProductAttribute
{
    public string ProductCode { get; set; }
    public string AttributeCode { get; set; }   // like "new", "sale", ...
    public DateTime ValidFrom { get; set; }
    public DateTime ValidTo { get; set; }
}

and the related

public DbSet Products { get; set; }
public DbSet ProductAttributes { get; set; }

I want to get the result in the form

public class Product2
{
   public string Code { get; set; }
   public string Name { get; set; }
   public decimal CatalogPrice { get; set; }
   
   public List? Attributes { get; set; } // the list of attribute codes
}

public DbSet Products2 { get; set; }

The attributes are valid only in certain period of time, and I want to get only subset of products to be displayed later -- that is skip some items and take the number of items.

I have no problem with getting the page for the Products. The problem is to get the page to Products2 -- with the list of attributes for each product. I do not know how to do that. I have played unsuccessfully with...

DateTime now = DateTime.Now;

var products2 = dbContext.Products
    .GroupJoin(dbContext.ProductAttributes,
               p => p.Code,
               a => a.ProductCode,
               (p, a) = new Product2
               {
                   Code = p.Code,
                   Name = p.Name,
                   CatalogPrice = p.CatalogPrice,
                   Attributes = ??? .Where(a => a.ValidFrom <= now 
                                           && now <= a.ValidTo)
                                    ??? having problem to refer the AttributeCode
                                    .ToList()
               }

How can I do that?

c# entity-framework-core ef-core-8.0