How to obtain column metadata from linq to Entities query? - linq

I need to support legacy client and compose ADO datasets from our Linq queries. The problem is how get specific column information (varchar length, decimal precision, etc) that cannot be obtained using reflection.
for example, I have table Customer with field Name varchar(80)
When I fetch data from linq to entities query:
var data = (from c in ctx.Customers select c.Name).ToList()
I cannot obtain maxSize for the column data[i].Name and adodataset raises an error.
I already have simple solution:
Code to extract column metadata from ObjectContext by property reference
Simple code that parses expression from Queryable and links output properties to edm columns.
But I have a lot of issues parsing complex queries that include multiple nested groupbys/unions/joins etc.
Does anybody know any other way (maybe using materialization shaper or similar)?

Thanks to EFProviderWrappers by Joseph Kowalski I have made similar provider and published it on codeplex

Related

Lightswitch 2013 Linq queries to Get min value

I'm writing a timesheet application (Silverlight) and I'm completely stuck on getting linq queries working. I'm netw to linq and I just read, and did many examples from, a Linq book, including Linq to Objects, linq to SQl and linq to Entities.(I assume, but am not 100% sure that the latter is what Lightswitch uses). I plan to study a LOT more Linq, but just need to get this one query working.
So I have an entity called Items which lists every item in a job and it's serial no
So: Job.ID int, ID int, SerialNo long
I also have a Timesheets entity that contains shift dates, job no and start and end serial no produced
So Job.ID int, ShiftDate date, Shift int, StartNo long, EndNo long
When the user select a job from an autocomplete box, I want to look up the MAX(SerialNo) for that job in the timesheets entity. If that is null (i.e. none have been produced), I want to lookup the MIN(SerialNo) from the Items entity for that job (i.e. what's the first serial no they should produce)
I realize I need a first or default and need to specify the MIN(SerialNo) from Items as a default.
My Timesheet screen uses TimesheetProperty as it's datasource
I tried the following just to get the MAX(SerialNo) from Timesheets entity:
var maxSerialNo =
(from ts in this.DataWorkspace.SQLData.Timesheets
where ts.Job.ID == this.TimesheetProperty.Job.ID
select ts.StartNo).Min();
but I get the following errors:
Instance argument: cannot convert from 'Microsoft.LightSwitch.IDataServiceQueryable' to 'System.Collections.Generic.IEnumerable
'Microsoft.LightSwitch.IDataServiceQueryable' does not contain a definition for 'Min' and the best extension method overload 'System.Linq.Enumerable.Min(System.Collections.Generic.IEnumerable)' has some invalid arguments
I also don't get why I can't use this:
var maxSerialNo = this.DataWorkspace.SQLData.Timesheets.Min(ts => ts.StartNo);
Can anyone point me in the right direction?
Thanks
Mark
IDataServiceQueryable doesn't support full set of LINQ operator like IEnumerable has.
IDataServiceQueryable – This is a LightSwitch-specific type that allows a restricted set of “LINQ-like” operators that are remote-able to the middle-tier and ultimately issued to the database server. This interface is the core of the LightSwitch query programming model. IDataServiceQueryable has a member to execute the query, which returns results that are IEnumerable. [Reference]
Possible solution is, execute your query first to get collection of type IEnumerable by calling .ToList(), then you can call .Min() against the first query result. But that isn't good idea if you have large amount of data, because .ToList() will retrieve all data match the query and do further processing in client side, which is inefficient.
Another way is, change your query using only operators supported by IDataServiceQueryable to avoid retrieving unnecessary data to client. For example, to get minimum StartNo you can try to use orderby descending then get the first data instead of using .Min() operator :
var minStartNo =
(
from ts in this.DataWorkspace.SQLData.Timesheets
where ts.Job.ID == this.TimesheetProperty.Job.ID
orderby ts.StartNo descending select ts
).FirstOrDefault();

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.

Shaping EF LINQ Query Results Using Multi-Table Includes

I have a simple LINQ EF query below using the method syntax. I'm using my Include statement to join four tables: Event and Doc are the two main tables, EventDoc is a many-to-many link table, and DocUsage is a lookup table.
My challenge is that I'd like to shape my results by only selecting specific columns from each of the four tables. But, the compiler is giving a compiler is giving me the following error:
'System.Data.Objects.DataClasses.EntityCollection does not contain a definition for "Doc' and no extension method 'Doc' accepting a first argument of type 'System.Data.Objects.DataClasses.EntityCollection' could be found.
I'm sure this is something easy but I'm not figuring it out. I haven't been able to find an example of someone using the multi-table include but also shaping the projection.
Thx,Mark
var qry= context.Event
.Include("EventDoc.Doc.DocUsage")
.Select(n => new
{
n.EventDate,
n.EventDoc.Doc.Filename, //<=COMPILER ERROR HERE
n.EventDoc.Doc.DocUsage.Usage
})
.ToList();
EventDoc ed;
Doc d = ed.Doc; //<=NO COMPILER ERROR SO I KNOW MY MODEL'S CORRECT
DocUsage du = d.DocUsage;
Very difficult to know what is going on without a screencap of your model, including the navigational properties on each entity.
But if your saying it's a many-to-many between Event and Doc (with EventDoc being the join table), and assuming your join table has nothing but the FK's and therefore doesn't need to be mapped, then shouldn't a single Event have many Doc's?
This query:
var query = ctx.Event.Include("EventDoc.Doc");
Would imply (based on the lack of pluralization): a single Event has a single EventDoc which has a single Doc.
But shouldn't that be: a single Event has a single EventDoc which has many Doc's.
Therefore your projection doesn't really make sense. Your trying to project to an anonymous type, with EventDate and Filename for a single Doc, but an Event has many Docs.
Maybe a projection like this would be more suitable:
var query = ctx.Event.Include("EventDoc.Docs.DocUsage")
.Select(x => new
{
EventDate = x.EventDate,
DocsForEvent = x.EventDocs.Docs
}).ToList();
And for that you work you need to fix up your model. Im surprised it even validates/compiles.
Either your model is wrong or your description of the database cardinalities in your question is. :)
Of course, i could be completely misunderstanding your database and/or model - so if i am let me know and i'll remove this answer.

Linq stored procedure with dynamic results

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

Using XQuery in Linq To SQL?

Let's say I have a table that has a column of XML type data. Within SQL, I can execute the following statement:
select top 10 *,
Content.value('(/root/item/value)[1]', 'float') as Value
from xmltabletest
where Content.value('(/root/item/MessageType)[1]', 'int') = 1
The result set contains only the records matching the criteria, and it extracts a value from the XML into a column called 'Value'. Nice and simple.
Can the same thing be achieved with Linq To SQL?
I'd like to get SQL to do the heavy lifting and only return data matching my criteria rather than having to select, transfer, and then process a potentially massive chunk of data. As far as I can tell this isn't possible at the moment, but I thought I should ask.
(The environment is .NET 3.5, VS2008, SQL Server 2005 if that helps)
I'm not exactly sure if this is out of date now, but according to Scott Guthrie XML datatypes are:
represented as strings in LINQ to SQL
Entities. You could use XLINQ to query
on an XML column within your LINQ to
SQL entitiy - but this querying would
happen in your middle-tier (within
ASP.NET). You can't execute a remote
XQuery against the database and filter
returned results based on that in the
first release.
So in answer to your question, I'd say "no."

Resources