Database Reference
In-Depth Information
using (var context = new EFRecipesEntities())
{
// using SqlQuery()
var result1 =
context.Resumes.SqlQuery
("select ResumeId, Title, Name,'' Body from chapter13.Resume",
"Resumes", MergeOption.AppendOnly).Single();
Console.WriteLine("Resume body: {0}", result1.Body);
var result2 =
context.Database.SqlQuery<Resume>("select * from chapter13.Resume", "Resumes",
MergeOption.OverwriteChanges).Single();
Console.WriteLine("Resume body: {0}", result2.Body);
}
Following is the output of the code in Listing 13-21:
Resume body:
Resume body: ...very long resume goes here...
How It Works
An approach for partially filling an entity is to use the SqlQuery() method that is exposed from the static Database
object, which can be accessed from the DbContext object. Here we execute a SQL statement that fills all of the
properties except for the Body property, which we initialize to the empty string. If needed, we can fill in the Body
property from the database by setting the MergeOption to MergeOption.OverwriteChanges and requerying for the
object for all of the properties. Be careful though, as the second query will overwrite any changes we've made to the
object in memory. Keep in mind that this approach exposes the SQL query as string, which yields no compile-time
checking or IntelliSense.
Recipe 13-8 shows a model-centric and perhaps cleaner approach to this problem.
13-8. Moving an Expensive Property to Another Entity
Problem
You want to move a property to another entity so that you can lazy load that entity. This is often helpful if the property
is particularly expensive to load and rarely used.
 
Search WWH ::




Custom Search