Home » .Net Framework

OData for Windows Phone 7 Problems with LinQ Queries

Hi, I posted some thread on the WP7 forum before I found this forum. Maybe here I could get more help.

See the original thread: http://social.msdn.microsoft.com/Forums/en-US/windowsphone7series/thread/62a6b89c-584a-42ac-ba85-ecec0a6f186b

I managed to get the proxy classes generated.

Data retrieval works if I just retrieve the complete collection.

If I ever try to filter data via a LinQ query in the LoadAsync script, I will be doomed. Exception.

For example:

var query from a in data.Entity where a.Name="Hello" select a;
works. Seems like a String constant makes no problem.

String param="Hello" param given as a function parameter to the following line:
var query from a in data.Entity where a.Name=param select a;

More complex queries will not work either - I try for example to get a match for a DateTime but no way...

Here is the dump the debugger gives me:

Expression:[10000].Select(o => o)
Expression2:[10000].Where(o => (o.Mahlzeit = value(MyDietLogWP7.ModelHandler+<>c__DisplayClass0).mahlzeit))
A first chance exception of type 'System.MethodAccessException' occurred in mscorlib.dll
A first chance exception of type 'System.MethodAccessException' occurred in System.Data.Services.Client.dll
Error:System.MethodAccessException: MethodAccessException
 at System.Reflection.RuntimeConstructorInfo.InternalInvoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, StackCrawlMark& stackMark)
 at System.Activator.InternalCreateInstance(Type type, BindingFlags invokeAttr, Binder binder, Object[] args, CultureInfo culture, StackCrawlMark& stackMark)
 at System.Activator.CreateInstance(Type type, Object[] args)
 at IQToolkit.ExpressionEvaluator.EvaluatorBuilder.Constant(ConstantExpression c)
 at IQToolkit.ExpressionEvaluator.EvaluatorBuilder.Build(Expression exp)
 at IQToolkit.ExpressionEvaluator.EvaluatorBuilder.MemberAccess(MemberExpression mLebensmittel Loaded

The first Expression is going through without a problem. The second will lead to the stacktrace above (the first query will not be executed in this example, but works if commented in).

DataServiceQuery<LebensmittelConsumed> lebQuery = (DataServiceQuery<LebensmittelConsumed>)
      from o in model.LebensmittelConsumedMenge
      select o;

   DataServiceQuery<LebensmittelConsumed> lebQuery2 = (DataServiceQuery<LebensmittelConsumed>)
      from o in model.LebensmittelConsumedMenge
      where o.Mahlzeit==mahlzeit
      select o;
   Debug.WriteLine("Expression:" + lebQuery.Expression);
   Debug.WriteLine("Expression2:" + lebQuery2.Expression);

3 Answers Found


Answer 1

Hi Shailan,

 The linq  interpreter on the phone  doesn't support closures on local variables, which means that using a variable inside a linq query  would cause runtime failures.
 This is an unfortunate bug and the only way to work  around this is to build the query in a string  and use the Execute<T> api to run the query.

 Here's a sample application which does this : 



Answer 2

Ok, understand, thx for the answer.

So you contruct the query-URL yourself and do the BeginExecute to fill in the data  from the service if I understand correctly.
Not as easy and nice as just throwing off a linq  request.

Is it planned to get this fixed either on the OData service or on the phones LinQ interpreter? Hope so as its working perfectly on SL already...




Answer 3

Any word on how close we are to having a fix for this? I'm writing a lot of extra code with conditional symbols that I'm looking forward to throwing out.



I'm using LINQ to oData with this query:

var query = from a in WorkflowTaskCollection where a.value == "1123" from c in a.DecisionOptionsCollection select c;

which translates to the following uri: WorkflowProcessing.svc/WorkflowTaskCollection(value='1123')/DecisionOptionsCollection()

but my service call fails with this uri as it expects: WorkflowProcessing.svc/WorkflowTaskCollection(value='1123')/DecisionOptionsCollection (not brackets at the end). what LINQ query can I write to get the uri without the brackets at the end?




 var queryOutput = from e in input.TumblingWindow(TimeSpan.FromSeconds(3), HoppingWindowOutputPolicy.ClipToWindowEnd)                                                    
                 select new { count = e.Count()};

Hi all,

I am just counting the events happening between a perticular period. I want to filter it. I need to count only the person's age is more than 60. I tried with "where".  But it is not working for me..

Eventype: EmpID,Age,GateNumber,EntryTime



I am using a LINQ query with multiple joins, the last join does not return any values even though values exist in the database. Below is my code.

when the query returns suiteNameTrg and SuiteTypeTrg are empty, all other values are returned correctly.

string suiteNameTrg = string.Empty;
            string suiteTypeTrg = string.Empty;
            using (DataClassesDataContext db = new DataClassesDataContext())
                    var productQuery = from assets in db.ASSETs
                    join relocatableUnits in db.RELOCATABLE_UNITs on assets.RUID equals relocatableUnits.RUID into assets_units
                    from relocatableUnits in assets_units.DefaultIfEmpty()
                   join build in db.BUILDINGs on assets.BUILDING_ID equals build.BUILDING_ID into assets_bins
                   from build in assets_bins.DefaultIfEmpty()
                   join test in db.TEST_SUITEs on assets.TEST_SUITE_ID equals test.TEST_SUITE_ID into test_bins
                   from test in test_bins.DefaultIfEmpty()
                    join testTrgt in db.TEST_SUITEs on assets.TARGET_TEST_SUITE_ID equals testTrgt.TEST_SUITE_ID into testTrgt_bins
                    from testTrgt in testTrgt_bins.DefaultIfEmpty()

                    select new

                                       suiteNameTrg = testTrgt.SUITE_NAME,
                                       suiteTypeTrg = testTrgt.SUITE_TYPE







i am using below lamda expression for getting accessory_cde if it matches to providing accessory description: It works fine if it matches to some data and in case of not matching , it

return nothing. How can i check it? how can i get value without using foreach loop.

var queryForAccessory = db_operations.ACCESSORY_CODEs.Where(p => p.accessory_dsc == accessories[i].Description)
                    .Select(a => new { a.accessory_cde });

also using LINQ query:
<span style="font-size:x-small"><font size="2"><p> </p></font></span><p><span style="font-size:x-small; color:#0000ff"><span style="font-size:x-small; color:#0000ff">var</span></span><span style="font-size:x-small"> query = </span><span style="font-size:x-small; color:#0000ff"><span style="font-size:x-small; color:#0000ff">from</span></span><span style="font-size:x-small"> a </span><span style="font-size:x-small; color:#0000ff"><span style="font-size:x-small; color:#0000ff">in</span></span><span style="font-size:x-small"> db_operations.ACCESSORY_CODEs<font size="2"></p><p> </p></font></span><p></p><p><span style="font-size:x-small; color:#0000ff"><span style="font-size:x-small; color:#0000ff">where</span></span><span style="font-size:x-small"> a.accessory_dsc == accessories[i].Description<font size="2"></p><p> </p></font></span><p></p><p><span style="font-size:x-small; color:#0000ff"><span style="font-size:x-small; color:#0000ff">select</span></span><span style="font-size:x-small"> </span><span style="font-size:x-small; color:#0000ff"><span style="font-size:x-small; color:#0000ff">new</span></span><span style="font-size:x-small"> { a.accessory_cde }; </span></p>






I have a simple LINQ query across my Entity Framework model like this:



var result1 = from p in ctx.Parts
               where p.DamageLine.RepairJob.ShopId == "1002"
               select p;

The problem with this is that it can take up to 50+ seconds to bring back 11 Parts records. I looked at the SQL output and it's selecting not only all the fields from Parts (which it should) but also including the DamageLine and RepairJob fields.

Any ideas?

David McCarter


I'm wanting to use the ToDictionary<..> syntax, but I want to not add duplicates.  The code I have that works is below.  any suggestions on how to do it in link?

 _dictionaryAllAttendeeResultByEmail = new Dictionary<string, AttendeesResult>();
      foreach (var attendee in attendeeResultsList)
        if (!_dictionaryAllAttendeeResultByEmail.ContainsKey(attendee.Email))
          _dictionaryAllAttendeeResultByEmail.Add(attendee.Email, attendee);


Suppose this scenario. 3 entities. Employee, Department, Empl_Dept (FK to Employee and FK to Department). Means an employee can belong to many departments.

Now I would like to determine the department all employees belong to or nothing if there no depatment all employees share.

Can you help me how to express this in LINQ To Entities?


I have listA and listB which basically contain lists of picture filenames.   listA would contain csm001.jpg, csm002.jpg, ...csm200.jpg   and listB would contain csm054.jpg, csm062.jpg...csm350.jpg.  I need to extract the filenames from each list which are matching filenames, like say both lists contain csm054.jpg and csm062.jpg (and others).  Originally, I just wanted to populate the lists as List<string> listA =... , List<string> listB = ...     but I couldn't find any linq samples to query just string lists, only object lists so I created a class object called myFile as follows:

public class myFile
  public string FileName;
  public myFile(string s)
    this.FileName = s;

and created List<myFile> listA = new List<myFile>();  List<myFile> listB = ...  and then populate the lists with myFile objects.  Here is/are the query(s) I tried for returning matching filenames -- which did not return any results:

//var query = listB.Where((x, i) => x.FileName == listA[i].FileName).ToArray();

//var query = from a in ListA join b in ListB on a.FileName equals b.FileName
       //select new { ListAItem = a, ListBItem = b };

var query = listA.Join(listB, a => a.FileName, b => b.FileName, (a, b) => new { ListAItem = a, ListBItem = b });

foreach (myFile m in query)  //--never goes into this loop -- no contents

First question is if I should just go with a straight list of strings List<string> listA... or if I should stay with the list of objects (is the class structure ok?), and the second question would be how I go about querying these lists to return the matching filenames.  listA contains 151 items and listB contains 104 items, for example, of which a few of the items in the lists are matching items.  I need to retrieve these matching items.






I have the following query:

https://odata.sqlazurelabs.com/OData.svc/v0.1/g08ao1qc91/AzurePoC/Readings()?$filter=(((Interval eq 524288) and (MeterId eq 'Total')) and (Moment gt datetime'2010-08-31T10:00:00+02:00')) and (Moment le datetime'2010-09-01T00:00:00+02:00')

I get a result set of 4 records. If i however make the constraints a little tighter, say:

https://odata.sqlazurelabs.com/OData.svc/v0.1/g08ao1qc91/AzurePoC/Readings()?$filter=(((Interval eq 524288) and (MeterId eq 'Total')) and (Moment gt datetime'2010-08-31T10:00:00+02:00')) and (Moment le datetime'2010-08-31T14:00:00+02:00')

I get a result set of 28 records. Now there is probably something i am doing wrong, but i can't for the life of me figure out why that first query won't return the same results as the second one + more. I used LinqPad to view the results, but the same happens in my Silverlight application.


Thanks for a quick fix for this issue. I hit another problemn almost immediatly however: when i try to orderby Moment, descending, i get a error 500 returned from the service.

Link you can use to try it with is: https://odata.sqlazurelabs.com/OData.svc/v0.1/g08ao1qc91/AzurePoC/Readings()?$filter=(Interval eq 524288) and (MeterId eq 'Total')&$orderby=Moment desc

If i get that working i would like the top 1 of that query: https://odata.sqlazurelabs.com/OData.svc/v0.1/g08ao1qc91/AzurePoC/Readings()?$filter=(Interval eq 524288) and (MeterId eq 'Total')&$orderby=Moment desc&$top=1

However i removed the top part to verify the problem lies with the orderby part.


I've bene using the DataServiceCollection to query my OData service so far. However I now need to create an anonymous type in my query (from a join where one part of the join is coming from a local collection of items) and return that collection. Is it possible to query a OData service when the LINQ expression returns an anymous type? I tried creating an class in my project that mirrors exactly the anonymous type's properties, but it isn't resolving...

Is this even possible? I'm not tied ot the DataServiceCollectoin in this instance... I just want to issue the query and get results... any alternatives? Here's what I've got so far...

DataServiceCollection<VideoInModule> _dataCollectionVideoInModule = new DataServiceCollection<VideoInModule>();

publicvoid GetModuleVideo(int moduleID, Action<IEnumerable<VideoInModule>> callback) {
 var query = from mv in ModuleVideoCollection
       where mv.ModuleID == moduleID
       selectnew {
        VideoID = mv.VideoID,
        OrderInModule = mv.ModuleVideoOrder
 var query2 = from video in videos
        join moduleVideo in query
        onnew { video.VideoID } equalsnew { moduleVideo.VideoID }
        selectnew {
         Video = video,
         OrderInModule = moduleVideo.OrderInModule

 // execute query
 _dataCollectionVideoInModule.LoadCompleted += (sender, e) => {
  List<VideoInModule> list = new List<VideoInModule>();
  foreach (var item in _dataCollectionVideoInModule) {
   list.Add(new VideoInModule { Video=item.Video, OrderInModule=item.OrderInModule});
 // this is the line that is tripping up as it doesn't like the query2 object being passed in... // says no overload method to match
publicclass VideoInModule {

 public Video Video { get; set; }
 publicint OrderInModule { get; set; }


Hi all,
I'm developing a Windows Phone application that consumes a WCF service. This WCF service (that hasn't been developed by me) simply returns an ObservableCollection of objects, which type is a custom class called PostDTO.
When I consume this WCF Service inside a Silverlight application, it works perfectly: the async method I call (named GetListAsync()) returns a collection of objects, that is displayed in the app using a ListBox.
When I consume the WCF service, instead, inside a WP7 app it doesn't work anymore: every time I launch the application, I get a ArgumentOutOfRangeException, specifically in the following method:
            public System.Collections.ObjectModel.ObservableCollection<PostDTO> EndGetList(System.IAsyncResult result) {
                object[] _args = new object[0];
                System.Collections.ObjectModel.ObservableCollection<PostDTO> _result = ((System.Collections.ObjectModel.ObservableCollection<PostDTO>)(base.EndInvoke("GetList", _args, result)));
                return _result;
The exception occurs in row 3 and the problem is that the var _result is null: if I debug the same proxy class inside the Silverlight application, instead, the var is not null, but correctly contains the ObservableCollection.
I've tried to change the type of collection returned by the method to a simple array, but the problem is still there.
I've tried also to copy the Reference.cs file from the Silverlight to the WP7 application (in case it's a problem of the proxy class generated by Visual Studio) but it doesn't work.
Any idea?
Thanks very much to anyone that will help me!
Matteo Pagani
Mobile Software Engineer



i'm binding 12 images dynamically through logic in that ~/Images/Image{0:00}.jpg  .But i want each individual image path and navigating that image paths to other page . i want logic for whenever click on particular image that image can be displayed in another page. 



i naviagte from one page(mainpage)  to another page (page1)then again after sometime navigate to mainpage in that i want values can't be reloaded to intial value.i.e values can't be changed even navigating to mainpage.

give me idea for that if possible sample code


I tried installing the beta but the installer fails with following message . I already have VS 2010 installed not sure why this is failing even to get started. :(

Visual Studio setup cannot run in compatibility mode.

For more information see the 'Installing' section in the Visual Studio Readme at "http://go.microsoft.com/fwlink/?LinkId=143397".



I have put a simple combobox in my phone page.

The code looks like this -




Grid x:Name="ContentGrid" Grid.Row="1">




<Grid x:Name="InnerGrid" Margin="24,24,24,24" VerticalAlignment="Stretch" Background="Transparent">








<RowDefinition Height="Auto"/>




<RowDefinition Height="Auto"/>




<RowDefinition Height="*"/>








<ComboBox x:Name="State" Grid.Row="0" />




<ComboBox x:Name="City" Grid.Row="1">




<ComboBoxItem Content="WINDOWS" />




<ComboBoxItem Content="PHONE7" />




<ComboBoxItem Content="TESTPHONE" />








<Button x:Name="ShowButton" Content="Show" Width="150" Height="72" Grid.Row="2" Margin="0,20,0,12" Click="ShowButton_Click"/>









But the problem is that when I run my application, the ComboBox items are not shown up in the Combo Box. Any idea why this is happening?



i'm added one image in applcation and change the icon path in wmappmanifest file to that image but that image can't be visible as launcher icon.

and also tried that image size as 62*62,90*90,173*173 various sizes images but no use.what's the mistake .


Does anybody know why I have a Memory problem?
Please see the screenshot for more information.
Item Value
OS Name Microsoft® Windows Vista™ Ultimate
Version 6.0.6002 Service Pack 2 Build 6002
Other OS Description Not Available
OS Manufacturer Microsoft Corporation
System Name CAT-PC
System Manufacturer Dell Inc.
System Model Latitude D630
System Type X86-based PC
Processor Intel(R) Core(TM)2 Duo CPU T7100 @ 1.80GHz, 1801 Mhz, 2 Core(s), 2 Logical Processor(s)
BIOS Version/Date Dell Inc. A03, 7/23/2007
SMBIOS Version 2.4
Windows Directory C:\Windows
System Directory C:\Windows\system32
Boot Device \Device\HarddiskVolume3
Locale United States
Hardware Abstraction Layer Version = "6.0.6002.18005"
User Name Cat-PC\James
Time Zone Eastern Daylight Time
Installed Physical Memory (RAM) 2.00 GB
Total Physical Memory 1.99 GB
Available Physical Memory 657 MB
Total Virtual Memory 4.21 GB
Available Virtual Memory 2.41 GB
Page File Space 2.28 GB
Page File C:\pagefile.sys



I try to install the Windows Phone Developer Tools RTW from http://create.msdn.com/en-us/home/getting_started . But at the end of the Installation a error occured "Setup could not install the following component: Microsoft Expression Blend 4 for Windows Phone".

In the log file it seems the setup try to install a German Version of Expression Blend on my system. I have only German regional settings, but all installed application are the english version (Windows 7, Office 2010, VS2010 all in english).

Have someone a solution?

Installation Log File (Office Live): http://goo.gl/0hyU



When I first installed and used windows phone app it displayed in full screen and looked rather nice. 

now all my videos are squished into this small , and poor quality, resolution that does not even come close to filling my samsungs focus full screen. 

I have yet to find any options to change this. Any ideas>?


<< Previous      Next >>

Microsoft   |   Windows   |   Visual Studio   |   Sharepoint   |   Azure