Creating Custom Class for LINQ to SQL Join Results

I’m currently dealing with two tables in my database: Product and Brand. I want to join these tables and send the data to my MVC view. At the moment, I’m using an anonymous type for this operation, but I’m considering switching to a strongly typed class.

I already have the entity classes for Product and Brand. Should I develop a new class, perhaps called ProductWithBrandInfo, to encapsulate the data from the join? What would be the best way to approach this situation?

Here’s how my existing query looks, which uses an anonymous type:

var result = from product in productTable
             join brand in brandTable on product.BrandId equals brand.BrandId
             where brand.BrandId == selectedBrandId
             select new
             {
                 product.ProductId,
                 product.Title,
                 product.Details,
                 product.Cost,
                 BrandTitle = brand.Title
             };

I would like to pass this information to my view in a way that is type-safe. Any advice on the best structure for this?

yeah, definitely go with strongly typed classes! anonymous types are a pain to debug, trust me. keep your ProductWithBrandInfo class simple for data holding tho, don’t mix in biz logic or it’ll get messy fast later on.

You’re absolutely right about creating a dedicated ProductWithBrandInfo class. I’ve done this in several projects and it’s a game-changer for type safety and maintainability. You get way better IntelliSense support and catch errors at compile time instead of runtime.

Just structure the class to match your anonymous type properties, then update your LINQ query to instantiate it directly in the select statement. Unit testing becomes much simpler too since you’re working with concrete types instead of anonymous objects.

One tip from experience: put these result classes in their own namespace or folder - maybe ViewModels or QueryResults. It keeps them separate from your entity classes, which really helps as your app grows.

interesting approach! have you thought about using a dto pattern instead? what do you do if you need different data combos for other views - create new classes for each case? i wonder how that impacts your codebase flexibility long-term.