Linq stored procedure with dynamic results - linq

So I'm extremely new to Linq in .Net 3.5 and have a question. I use to use a custom class that would handle the following results from a store procedure:
Set 1: ID Name Age
Set 2: ID Address City
Set 3: ID Product Price
With my custom class, I would have received back from the database a single DataSet with 3 DataTables inside of it with columns based on what was returned from the DB.
My question is how to I achive this with LINQ? I'm going to need to hit the database 1 time and return multiple sets with different types of data in it.
Also, how would I use LINQ to return a dynamic amount of sets depending on the parameters (could get 1 set back, could get N amount back)?
I've looked at this article, but didn't find anything explaining multiple sets (just a single set that could be dynamic or a single scalar value and a single set).
Any articles/comments will help.
Thanks

I believe this is what you're looking for
Linq to SQL Stored Procedures with Multiple Results - IMultipleResults

I'm not very familiar with LINQ myself but here is MSDN's site on LINQ Samples that might be able to help you out.

EDIT: I apologize, I somehow missed the title where you mentioned you wanted help using LINQ with Stored Procedures, my below answer does not address that at all and unfortunately I haven't had the need to use sprocs with LINQ so I'm unsure if my below answer will help.
LINQ to SQL is able hydrate multiple sets of data into a object graph while hitting the database once. However, I don't think LINQ is going to achieve what you ultimately want -- which as far as I can tell is a completely dynamic set of data that is defined outside of the query itself. Perhaps I am misunderstanding the question, maybe it would help if you provide some sample code that your existing application is using?
Here is a quick example of how I could hydrate a anonymous type with a single database call, maybe it will help:
var query = from p in db.Products
select new
{
Product = p,
NumberOfOrders = p.Orders.Count(),
LastOrderDate = p.Orders.OrderByDescending().Take(1).Select(o => o.OrderDate),
Orders = p.Orders
};

Related

Nhibernate Update timestamp

Is there a way to do
"UPDATE Item SET start_date = CURRENT_TIMESTAMP" ?
in Nhibernate without using hql/sql.
I am trying to avoid hql/sql because the rest of my code is in criteria. I want to do something like :
var item = session.get<Item>(id)
item.start_date = current_timestamp
There are two ways and sql is correct one.
Either you will
load all entities, change, update and commit, or
write sql query and let dbms handle most of the work
I am trying to avoid hql/sql because the rest of my code is in criteria
That is not a valid argument. Criteria is an API intended for relational search, and it does not support mass updates.
Different tasks, different APIs.
In this case, you can use either HQL or SQL, as the syntax is the same. I recommend the former, because you'll be using your entity/property names instead of table/column ones.

How to use calculated fields in my LightSwitch Query?

in my lightswitch application im trying to create a Customers Screen for customers who have balance value, and my balance value is a Calculated Field in the Customer Entity
when i tried to put the logic in the Process Query Event Like This
query =( from i in query
where(i.Balance>0)
select i );
i get an exception .. what is the best way to handle these kind of situations ??
i saw an answer here but i didn't know how to implement it exactly i need a sample code for it can anyone help me ??
thanks in advance
The query will be executed by the data provider, which doesn't know about calculated fields. What you can do is to filter what you want via LINQ, referring to the actual fields, not the calculated ones.
For example, let's say Balance is your calculated field, that you defined as Credit - Debit (which are normal fields). You want your query to return the rows where Balance > 0. This is how you'd write the query (in the PreprocessQuery event, note there is no ProcessQuery event):
partial void TestQuery_PreprocessQuery(ref IQueryable<Customer> query)
{
query = (
from c in query
where ((c.Credit - c.Debit) > 0)
select c);
}
Another theoretical way of solving the problem would be setting a filter in the Executed event handler. However, for whatever the reason, when I do it, the filter is not applied to the screen. But even if this method would work, still you'd be filtering on the client side, which might not be what you want.
I'm actually looking for a solution to this problem
(unfortunately I can't just include the calculation from the calculated field, because my calculation uses another calculated field which uses recursion)
A couple of pointers I thought you might find helpful:
#julio.g - for the Executed event handler, the "result" parameter is an IEnumerable parameter (as opposed to the PreProcess_Query event handler, where the "query" parameter is a ref IEnumerable) so any changes you make to the "result" will only be local to that method
#3oon - afaik, SQL Views are not supported in LightSwitch. The best option I've come across so far is to create a WCF RIA Service based on a Stored Procedure, then adding it as a datasource.
This blog post should help get you started.
http://tejana.wordpress.com/2010/12/09/microsoft-lightswitch-and-stored-procedures-using-wcf-ria-services/
Hope that helps!

Help to convert the SQL query to Lambda(Linq)

Can anyone help me, to convert the below sql query to Linq (Lambda Expressions).
Thanks in Advance.
SQL Query:
UPDATE A INNER JOIN B ON (A.Trade Number=B.Trade Number) AND
(A.AccountId=B.AccountId) SET A.Float = B.CCY, A.Float = B.BASIS,
A.LastReset = B.FIXING, A.LastLibor = B.INTRATE;
Updates are not expressed as LINQ statements. You can use LINQ to load the record you wish to modify, but the actual update will involve a separate method call, the details of which will depend on which database technology you're using.
So, assuming you already have a reference to the record you wish to update from A, load the associated record from B (using LINQ), perform the updates to A programatically, and then save the changes to A.
Here's an example using LINQ-to-SQL.

Linq equivalent of SQL LEFT function?

We have a database with some fields that are varchar(max) which could contain lots of text however I have a situation where I only want to select the first for example 300 characters from the field for a paginated table of results on a MVC web site for a "preview" of the field.
for a simplified example query where I want to get all locations to display in the table
(this would be paginated, so I don't just get everything - I get maybe 10 results at a time):
return db.locations;
However this gives me a location object with all the fields containing the massive amounts of text which is very time consuming to execute.
So what I resorted to before was using SQL stored procedures with the:
LEFT(field, 300)
to resolve this issue and then in the Linq to SQL .dbml file included the stored procedure to return a "location" object for the result.
However I have many queries and I don't want to have to do this for every query.
This maybe a simple solution, but I am not sure how I can phrase this on a search engine, I would appreciate anyone who can help me with this problem.
You can use functions that directly translate to those functions too, this is useful when you need to translate code that functionally works just fine in SQL at no risk in LINQ.
Have a look at System.Data.Objects.EntityFunctions
Locations.Select(loc=>System.Data.Objects.EntityFunctions.Left(loc.Field,300))
This will get directly translated into a LEFT on the server side.
EDIT: I misread LEFT for LTRIM. Here's all the String functions that can't be used in LINQ to SQL. Have you tried String.Substring()?
Your best option is to map the stored procedure and continue using it. Here is an excellent article with screen shots showing you how to do so.
If you're not using the designer tool you can also call ExecuteCommand against the DataContext. It isn't pretty, but it's what we have for now.
I found something like this worked for me:
return from locationPart in db.locations
select new LocationPart
{
Description = locationPart.description,
Text = locationPart.text.Substring(0,300)
};
Not ideal because I have to use "select new" to return a a different object, but it seems to work.

LINQ and Generated sql

suppose my LINQ query is like
var qry = from c in nwEntitiesContext.CategorySet.AsEnumerable()
let products = this.GetProducts().WithCategoryID(c.CategoryID)
select new Model.Category
{
ID = c.CategoryID,
Name = c.CategoryName,
Products = new Model.LazyList<Core.Model.Product>(products)
};
return qry.AsQueryable();
i just want to know what query it will generate at runtime....how to see what query it is generating from VS2010 IDE when we run the code in debug mode....guide me step by step.
There is not much to see here - it will just select all fields from the Category table since you call AsEnumerable thus fetching all the data from the Category table into memory. After that you are in object space. Well, depending on what this.GetProducts() does - and my guess it makes another EF query fetching the results into memory. If that's the case, I would strongly recommend you to post another question with this code and the code of your GetProducts method so that we can take a look and rewrite this in a more optimal way. (Apart from this, you are projecting onto a mapped entity Model.Category which again won't (and should not) work with Linq-to-Entities.)
Before reading into your query I was going to recommend doing something like this:
string sqlQueryString = ((ObjectQuery)qry).ToTraceString();
But that won't work since you are mixing Linq-to-Entities with Linq-to-objects and you will actually have several queries executed in case GetProducts queries EF. You can separate the part with your EF query and see the SQL like this though:
string sqlString = nwEntitiesContext.CategorySet.ToTraceString();
but as I mentioned earlier - that would just select everything from the Categories table.
In your case (unless you rewrite your code in a drastic way), you actually want to see what queries are run against the DB when you execute the code and enumerate the results of the queries. See this question:
exact sql query executed by Entity Framework
Your choices are SQL Server Profiler and Entity Framework Profiler. You can also try out LinqPad, but in general I still recommend you to describe what your queries are doing in more detail (and most probably rewrite them in a more optimal way before proceeding).
Try Linqpad
This will produce SELECT * FROM Categories. Nothing more. Once you call AsEnumerable you are in Linq-to-objects and there is no way to get back to Linq-to-entities (AsQueryable doesn't do that).
If you want to see what query is generated use SQL Profiler or any method described in this article.

Resources