I've got an SQL table that stores a person record where one column is an image. I'm using the table in an ASP.Net MVC application and I only want to retrieve the image column in the controller action that is used by my HTML image source attribute.
How can I prevent the column storing the image from being retrieved by my LINQ query without having to resort to explicitly requesting every desired column but still be able to retrieve it with an explicit request?
This is the LINQ expression I don't want to return the image column in (there are about a dozen includes so explicitly specifying each property is not an option):
Person person = (from per in entities.People.Include(...).Include(..)
where per开发者_如何学运维.ID == id
select per).FirstOrDefault();
The LINQ expression I use to get the image is:
byte[] picture = (from per in entities.People
where Per.ID == id
select per.Picture).FirstOrDefault();
You must use table splitting. The point of table splitting is that you don't touch your database but you map multiple entities to single table.
Your Person
entity will not contain Image
anymore but instead it will contain navigation property to PersonImage
entity. The new entity will contain only Id
(same as related person => one-to-one relation) and Image
. A navigation property can be loaded only if needed. You can't avoid loading a scalar property unless you use a projection or query view (which you probably don't want to use).
Given that there are plenty of reasons to split a table when you have one large but rarely used section of it, why solve this on the code side? Your best option is probably to break the images off in a separate table which is linked to the first. Your sql server will be happier and your code will be cleaner.
Depending on how you're using EF4 (Database-first? Model-first?), you may be able to make a view (and another entity) that doesn't contain your image. Or you can use a defining query on your Model side: http://blogs.msdn.com/b/davidebb/archive/2010/10/01/the-easy-way-to-create-an-entity-framework-defining-query.aspx
var smallPerson = from per in entities.People.Include(...).Include(..)
where per.ID == id
select new Person() {
.Name = per.Name,
.Surname = per.Surname
}).FirstOrDefault();
Alternatively just return an anonymous type using this similar method. This object will be read only.
var smallPerson = from per in entities.People.Include(...).Include(..)
where per.ID == id
select new {
.Name = per.Name,
.Surname = per.Surname
}).FirstOrDefault();
精彩评论