Tip 40 – How to materialize presentation models via L2E
Problem:
Imagine that you have these entities
public class Product
{
public int ID { get; set; }
public string Name { get; set; }
public virtual Category Category { get; set; }
}
public class Category
{
public int ID { get; set; }
public string Name { get; set; }
public virtual List<Product> Products { get; set; }
}
But for your UI you want to display the product id, product name and the product’s category’s name.
You might try passing this query to the presentation layer.
var displayData = from product in ctx.Products.Include("Category")
select product;
But then you are passing more than is required around, and binding the UI tightly to the conceptual model, which is probably a bad idea.
Your next try might be a query like this:
var displayData = from product in ctx.Products
select new {
ID = product.ID,
Name = product.Name,
CategoryName = product.Category.Name
};
But then you’ll quickly discover you can’t pass the anonymous types to another method, at least not without a nasty hack.
Solution:
Most people think LINQ to Entities can only materialize Entities and Anonymous types.
But in fact it turns out it can materialize any non-generic class that has a default constructor.
Anyway what this means is you can create a view class like this:
public class ProductView
{
public int ID { get; set; }
public string Name { get; set; }
public string CategoryName { get; set; }
}
And then write this:
var displayData = from product in ctx.Products
select new ProductView {
ID = product.ID,
Name = product.Name,
CategoryName = product.Category.Name
};
And then pass this to your view without any problems at all.
I only just found out about this myself, I had always assumed this would fail.
So this was a nice pleasant surprise.