matt
matt

Reputation: 2997

Retrieving all values as strings from SQL Server

I'm currently using EF Code-First, and I'd like to SELECT data from many tables in the database. This query is a customizable query, and hence I can't predict what kind of data I will be retrieving.

At first, when I tried running ctx.Database.SqlQuery<string>(sql, param), I ran into an exception when facing a DateTime value. I'd like to do this without casting it on the server side.

Does anybody have any idea how I can go about doing it? It can be in LINQ, LINQ-SQL, or purely SQL--so long as it gets the job done! Thanks guys...

Upvotes: 2

Views: 150

Answers (3)

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364259

You will not get it. Linq-to-entities will not make transformation to list of strings. Your best chance is executing normal queries and do conversion and transformation your application.

Argument that you don't know which columns user selects just means you need more dynamic solution - Linq-to-entities is not a good tool for you (except if you try to use Dynamic Linq or build expression trees manually). Use ESQL or SQL directly.

Upvotes: 1

Zaheer Ahmed
Zaheer Ahmed

Reputation: 28528

You can achieve string values by casting your data fields to string in this way:

var query = _db.Categories.Join(
_db.Products,
c => c.CategoryId,
p => p.CategoryId,
(category, product) =>
   new
   {
       ProductName = product.Name.toString(),
       CategoryName = category.Name.toString(),
       ExpiryDate = product.ExpiryDate.toString()
   });

Upvotes: 0

Mahmoud Gamal
Mahmoud Gamal

Reputation: 79919

When selecting data from many tables, use anonymous types to encapsulate the properties(fields) you want to select from these tables into a new entity, something like:

var query = _db.Categories.Join(
_db.Products,
c => c.CategoryId,
p => p.CategoryId,
(category, product) =>
   new
   {
       ProductName = product.Name,
       CategoryName = category.Name,
       ExpiryDate = product.ExpiryDate
   });

Upvotes: 0

Related Questions