Linq with entities - wcf

I am starting to develop a system using silverlight 5 with wcf ria. I use Visual studio 2010 and the code is in visual basic. In my application I have a table guiasidiomas. It is a very simple table:
Id
Idguia
Ididioma
In the application I changed the query getguiasidiomas that is generated by the domain service
Public Function GetGuiasIdiomas(ByVal idProcurado As String) AsIQueryable(Of GuiasIdioma)
Return Me.ObjectContext.GuiasIdiomas.Where(Function(c) (c.idGuia).ToString = idProcurado)
End Function
I inserted a where in order to filter by a given idguia.
That is the query that has a problem.
If you could help me I would appreciate very much.
When I run the query I get:
SCRIPT5022: Unhandled Error in Silverlight Application
Code: 4004
Category: ManagedRuntimeError
Message: System.ServiceModel.DomainServices.Client.DomainOperationException: Load operation failed for query 'GetGuiasIdiomas'. LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression.

Linq-to-Entities cannot translate .ToString() directly to SQL, so you cannot use it in your WHERE clause. Here are two options:
Convert idProcurado to the same datatype as idGuia and compare directly
Pull ALL entities from the database (e.g. by calling .AsEnumerable()) and doing the comparison against the object list.
I'm guessing 1) is going to give you better performance by only puling back one or a small number of entities.

As your error message says, linq to entities does not support ToString.
You can prepare list of strings before using it with linq to entities.

Related

How does a Queryable Load work in SharePoint?

Could anybody help me to understand what kind of work is going behind the scene, when LINQ is used for retrieving SharePoint objects. For example, I can use a code like this:
private IEnumerable<List> newLists;
var dt = new DateTime(2010, 3, 20);
var query = from list
in clientContext.Web.Lists
where list.Created > dt && list.Hidden == false
select list;
newLists = clientContext.LoadQuery(query);
clientContext.ExecuteQuery();
How does it work?
How does request look like?
From documentation I found:
When you use the CSOM, you can write LINQ queries against client-side
objects, such as lists and Webs, and then use the ClientContext class
to submit these queries to the server. It's important to understand
that when you take this approach, you are using LINQ to Objects to
query SharePoint objects, not LINQ to SharePoint. This means that your
LINQ expressions are not converted to CAML and you will not see the
performance benefits that are associated with CAML conversion.
So, I was little bit confused, because I thought, that LINQ expression is transformed to Caml request. I can't understand how does it work. How can I watch details of request while executing ExecuteQuery() method? Could you please recomend me any tools for watching requests?
SP uses CAML internally: SP runtime converts Linq to CAML and send it via Soap request, or REST statement (if you are using RESTful services): http://msdn.microsoft.com/en-us/library/ff798339.aspx (with examples);
See more here:
http://msdn.microsoft.com/en-us/library/ff798464.aspx
and this can be helpful: http://nikspatel.wordpress.com/2012/08/05/sharepoint-2010-data-querying-options-server-om-vs-client-om-vs-rest-vs-linq-vs-search-api/

ORM for Spring-MongoDB integration with native querying support

I am a new to using Mongo DB and exploring the frameworks around for migrating from mysql to mongodb. So far from my findings I have been able to figure out SpringMongo as the best solution to my requirements.
The only problem is that instead of using a DSL based or abstract querying mechanism, I wished the framework allowed me to pass plain json string as arguments to the different methods exposed by the API(find, findOne) so that the query parameters can be written out to an external file (using a key to refer) and passed to the methods by reading and parsing at run time. But the framework should be capable of mapping the results to the domain objects.
Is there a way in spring-mongo to achieve this? Or is there any other frameworks on the same lines
You could use Spring Data to do that, just use the BasicQuery class instead of Query class. Your code will look like the following:
/* Any arbitrary string that could to parsed to DBObject */
Query q = new BasicQuery("{ filter : true }");
List<Entity> entities = this.template.find(q, Entity.class);
If you want more details:
http://static.springsource.org/spring-data/data-mongo/docs/current/reference/html/#mongo.query
http://static.springsource.org/spring-data/data-mongodb/docs/current/api/org/springframework/data/mongodb/core/query/BasicQuery.html
Well I got to find this one in the Spring data MongoOperations...
String jsonCommand = "{username: 'mickey'}";
MongoOperations mongoOps = //get mongooperations implemantation
mongoOps.executeCommand(jsonCommand)
It returns an instance of CommandResult that encapsulates the result.

Native Query Mapping on the fly openJPA

I am wondering if it is possible to map a named native query on the fly instead of getting back a list of Object[] and then looping through and setting up the object that way. I have a call which I know ill return a massive data set and I want to be able to map it right to my entity. Can I do that or will I have to continue looping through the result set.
Here is what I am doing now...
List<Provider> ObjList = (List<Provider>) emf.createNativeQuery(assembleQuery(organizationIDs, 5)).getResultList();
That is my entity, the List (my entity is the provider). Normally I would just return a List<Object[]>
and then I would loop through that to get back all the objects and set them up as new providers and add them to a list....
//List<Provider> provList = new ArrayList<Provider>();
/*for(Object[] obj: ObjList)
{
provList.add(this.GetProviderFromObj(obj));
}*/
As you can see I commented that section of the code out to try this out. I know you can map named native queries if you put your native query in the entity itself and then call it via createNamedQuery. I would do it that way, but I need to use the IN oracle keyword because I have a list of ID's that I want to check against. It is not just one that is needed. And as we all know, native queruies don't handle the in keyword to well. Any advice?
Sigh, If only the IN keyword was supported well for NamedNativeQueries.
Assuming that Provider is configured as a JPA entity, you should be able to specify the class as the second parameter to your createNativeQuery call. For example:
List<Provider> ObjList = (List<Provider>) emf.createNativeQuery(assembleQuery(organizationIDs, 5), Provider.class).getResultList();
According to the documentation, "At a minimum, your SQL must select the class' primary key columns, discriminator column (if mapped), and version column (also if mapped)."
See the OpenJPA documentation for more details.

Problem with RavenDB 'Hello World' tutorial

I am going through the RavenDB tutorial on the RavenDb.net website.
It was going fine until I got to the code block for creating an index.
This code segment is direct from RavenDB.Net website.
store.DatabaseCommands.PutIndex("OrdersContainingProduct", new IndexDefinition<Order>
{
Map = orders => from order in orders
from line in order.OrderLines
select new { line.ProductId }
});
I get an error on compile: "The non-generic type 'Raven.Database.Indexing.IndexDefinition' cannot be used with type arguments."
If IndexDefinition is non-generic, why is it used as generic in the sample code? Where is the disconnect?
Thank you for your time
Jim
Depending on your using statements you may be referencing the wrong IndexDefinition class (from another Raven assembly). Try adding this to the beginning of your file:
using Raven.Client.Indexes;
You might need to remove other using statements as well. I guess this is one reason why Microsoft recommends using unique names for classes even in the presence of namespaces.

Stored Proc in RIA Services

I want to load some data with a SP.
I've put a SP in a Linq to SQL Class and I don't know how to use it for loading it's data in a datagrid.
In LinqToSqlDomainService I can't figure out how to call a SP.
What steps should I use.
Any samples of this ? All samples use a table.
Thank's
This post should hopefully be of help:
http://blogs.msdn.com/brada/archive/2009/08/24/business-apps-example-for-silverlight-3-rtm-and-net-ria-services-july-update-part-24-stored-procedures.aspx
You can create empty view with the same structure of your sproc and map that stored procedure to your function in your DomainService
See sample on http://cid-289eaf995528b9fd.skydrive.live.com/self.aspx/Public/sproc.zip
I found the following excellent step-by-step guide at this site -
http://betaforums.silverlight.net/forums/p/218383/521023.aspx
1) Add a ADO Entity Data Model to your Web project; Select generate from database option; Select your Database instance to connect to.
2) Choose your DB object to import to the Model. You can expand Table node to select any table you want to import to the Model. Expand Stored Procedure node to select your Stored Precedure as well. Click Finish to finish the import.
3) Right click the DB model designer to select Add/Function Import. Give the function a name (same name as your SP would be fine) and select the Stored Procedure you want to map. If your SP returns only one field, you can map the return result to a collection of scalars. If your SP returns more than one field, you could either map the return result to a collection or Entity (if all the field are from a single table) or a collection of Complex types.
If you want to use Complex type, you can click Get Column button to get all the columns for your SP. Then click Create new Complex type button to create this Complex type.
4) Add a Domain Service class to the Web project. Select the DataModel you just created as the DataContext of this Service. Select all the entitis you want expose to the client. The service functions should be generated for those entities.
5) You may not see the Complex type in the Entity list. You have to manully add a query function for your SP in your Service:
Say your SP is called SP1, the Complex type you generated is called SP1_Result.
Add the following code in your Domain Service class:
public IQueryable<SP1_Result> SP1()
{
return this.ObjectContext.SP1().AsQueryable();
}
Now you can compile your project. You might get an error like this: "SP1_Result does not have a Key" (if you not on RIA service SP1 beta). If you do, you need to do the following in the service metadata file:
Added a SP1_Result metadata class and tagged the Key field:
[MetadataTypeAttribute(typeof(SP1_Result.SP1_ResultMetadata))]
public partial class SP1_Result
{
internal sealed class SP1_ResultMetadata
{
[Key]
public int MyId; // Change MyId to the ID field of your SP_Result
}
}
6) Compile your solution. Now you have SP1_Result exposed to the client. Check the generated file, you should see SP1_Result is generated as an Entity class. Now you can access DomainContext.SP1Query and DomainContext.SP1_Results in your Silverlight code. You can treat it as you do with any other Entity(the entity mapped to a table) class.
Calling a stored procedure is trivial. Import it as a function and then invoke the function as a member of the DDS. The return value is an ObservableCollection<> that you can use to set up the DataContext of the object you want to bind.
...unless you want to use it in a Silverlight RIA app via the magic code generated proxy, in which case your goose is cooked unless your result rows exactly match one of the entities. If you can meet that criterion, edit the DomainService class and surface a method that wraps the ObjectContext method.