I work on an ASP.NET MVC product, using EF 4.3 with lazy loading enabled.
I’ve got a class Product, that can have zero or more Attachments:
public class Product
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public virtual long Id { get; set; }
//... other properties
public virtual List<Attachment> Pictures { get; set; }
}
public class Attachment
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public virtual long Id { get; set; }
[Required]
public virtual byte[] Data { get; set; }
}
My primary page (HTML) will serve product details, including a list of the attachments. For the latter, I only require the attachment’s id, and explicitly don’t want to load the Data property (which can be a lot of data).
How do I write a query that will only return the attachment’s id’s, and will not query the database for attachment’s data property?
The query below was not successful; error: Unable to create a constant value of type ‘XXX.Model.Attachment’. Only primitive types (‘such as Int32, String, and Guid’) are supported in this context.
var query = from a in db.Attachments
from prod in db.Product
from pic in prod.Pictures
where prod.Id == prodId && a.Id == pic.Id
select a.Id;
query.ToList();
And the following did load the attachment’s data field:
var product = db.Products.Find(prodId);
var pictureIds = product.Pictures.Select(x => x.Id).ToList();
Try this:
or