Print Page | Close Window

Use PassthruEsqlQuery to return 2 columns from an Entity

Printed From: IdeaBlade
Category: DevForce
Forum Name: DevForce 2009
Forum Discription: For .NET 3.5
URL: http://www.ideablade.com/forum/forum_posts.asp?TID=1236
Printed Date: 29-Apr-2025 at 9:23pm


Topic: Use PassthruEsqlQuery to return 2 columns from an Entity
Posted By: Archvile
Subject: Use PassthruEsqlQuery to return 2 columns from an Entity
Date Posted: 28-Apr-2009 at 11:27am
Hi,
 
I am struggling with this for some time and finally caved in. This is what I need :
 
I have an Entity called Student with 5 columns. I need only the first and the last names to be selected. I am using the following query and code: 
 
var sql = "select s.fName as First, s.lName as Last FROM Student as s";

var pass0 = new PassthruEsqlQuery(typeof(Student), sql);

var return = pass0.With(manager.EntityManager).Execute();
 
When I execute this I get an error:
The specified cast from a materialized 'System.Data.Objects.MaterializedDataRecord' type to the ..ObjectModel.Student type is not valid..
 
Any suggestions?
- arch



Replies:
Posted By: kimj
Date Posted: 29-Apr-2009 at 9:09am

You're not going to be able to use a PassthruEsqlQuery for this, since the query is not returning a Student entity. 

However, you can easily create a projection with a LINQ query -
 
   var query = _entityManager.Student
                      .Select(s => new { s.fName, s.lName });
 
or if you prefer query syntax:

   var query = from s in _entityManager.Student
                      select new { s.fName, s.lName };
These queries return an anonymous type containing only the selected properties.
 
If you must use a passthru query for some reason, then you'll need to create a view containing only the table columns wanted, and then define an entity type based on that view.
 


Posted By: Archvile
Date Posted: 29-Apr-2009 at 9:16am
Thanks kimj, I was aware of the linq projection, wanted to know the Passthru.
Thanks for your response.
 
- arch



Print Page | Close Window