简体   繁体   中英

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...

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.

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
   });

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()
   });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM