linq,asp.net-web-api , Can't access any of Linq methods


Can't access any of Linq methods

Question:

Tag: linq,asp.net-web-api

I'm writing a simple ApiController for getting product stocks, but I'm having a strange issue. I get the data from a method that returns a System.Linq.IQueryable (In a library), but I can't apply any of the Linq methods, like Count or ToList(). The import directive is present and doesn't report any problem. Also intellisense shows Data as System.Linq.IQueryable.

The code:

Imports System.Web.Http
Imports System.Linq

Public Class ProductSearchController
    Inherits ApiController

    Public Function Get(...) As IQueryable

        Dim nvc As NameValueCollection = HttpUtility.ParseQueryString(Request.RequestUri.Query)
        Dim sEcho As String = nvc("sEcho").ToString()
        Dim iDisplayStart As Integer = CType(nvc("iDisplayStart"), Integer)

        'Signature of Stock:  public IQueryable Stock(...)
        Dim Data = New GenericSearches().Stock(...)
        Dim Count As Integer = Data.Count() 'Error Here!

        Dim result = New DataTableResult With {
            .sEcho = sEcho,
            .iTotalRecords = Count,
            .iTotalDisplayRecords = Count,
            .aaData = Data.ToList() 'Error Here!
            }
        Return result
    End Function
End Class

Also, I noticed that error correction and intellisense asks me to choose those methods from a weird Devexpress library something like DevXpress.Data.Helpers.Linq.


Answer:

The non-generic IQueryable interface doesn't have extension methods of Count and ToList(). Only the generic IQueryable<T> does.

If you can modify the library to return a suitable IQueryable<T>, I suggest you do so. If you can't, you may need to call Cast<T>() or OfType<T>() to create an appropriate IQueryable<T> with the right extension methods.


Related:


Passing conditional parameters to Database.SqlQuery


c#,sql,linq,entity-framework
I have been doing the following to pass parameters with my sql query: var retval = context.MyObject.SqlQuery(sql.ToString(), new SqlParameter("@ProductId", productId), new SqlParameter("@CustomerId", customerId)).ToList(); I ran into a scenario where @CustomerId will not always be used in my sql string. Meaning I used an if statement to either add (Where p.CustomerId...

Why does .Where() with a Func parameter executes the query?


c#,oracle,linq,entity-framework
Here's how my DataAccessLayer works : public Foo GetFooBy(Func<Foo, bool> filter) { var query = from item in this.DataService.FooSet select item; var where = query.Where(filter); var first = where.First(); return first; } I assumed the query would be run when First() is called but it's actually executed by the Where()....

Cannot get data using LINQ in MVC


c#,asp.net-mvc,linq,asp.net-mvc-4
I'm trying to get data in autocomplete from JsonResult Action Method in my controller. I cannot query data with LINQ, I'm sharing code please guide me. Action Method public class VehicleController : Controller { private readonly IService<Vehicle> _service; public VehicleController(IService<Vehicle> service) { _service = service; } public JsonResult AutoComplete(string term)...

How to write Nested LINQ for specific scenario


c#,linq
Apologized to post a problem for which i could not construct anything solid. it is very shameful for me to post like this kind of question even after having so high reputation for this web site. Most of the time i write sql in store procedure in sql server and...

Passing complex array from Controller to View ASP.NET MVC


c#,asp.net,asp.net-mvc,asp.net-web-api
I have a model in my ASP.NET MVC application: public class SearchArrayModel { public long ID { get; set; } public string Name { get; set; } public struct AttribStruct { public string AttribName { get; set; } public string[] AttribValues { get; set; } } public AttribStruct[] AttribStructTable {...

orderby () containing numbers and letters


c#,wpf,linq,linq-to-sql,sql-order-by
I want to order an array containing numbers and letters in an ascending order the values are stored as a string in a DB. This is the list I have 4B 1A 1 1B 2 4C 4 and want them to order like this where numbers are ascending followed by...

Issue displaying LINQ query results in a grid in C#


c#,linq
I received some help here with the following LINQ query, but am still struggling with it. The result I'm trying to obtain is to display some attributes and their values from an xml file in a DataGridView control. I'm calling my method from a button click and am trying to...

Please help me convert this sql to LINQ


linq
DECLARE @items table ( pfid varchar(8), timestart datetime, timeend datetime ) insert INTO @items(pfid,timestart,timeend) VALUES('123456','12:00 AM','3:00 AM') ,('987654', '2:00 AM', '4:00 PM') ,('492384', '3:00 PM', '9:00 PM') SELECT * FROM @items a INNER JOIN @items b ON a.timestart < b.timeend AND b.timestart < a.timeend AND a.pfid != b.pfid I need...

Linq Conditional DefaultIfEmpty query filter


c#,linq,asp.net-mvc-5,linq-query-syntax
I have a query as below: bool variable = false//or true var query = from e in _repository.GetAll<Entity>() from u in e.Users where (e.AuditQuestionGroupId != null ? e.AuditQuestionGroupId : 0) == this.LoggedInEntity.AuditQuestionGroupId from p in e.PractitionerProfiles.DefaultIfEmpty() select new { entity = e, user = u, profile = p }; This...

How to declare var datatype in public scope in c#?


c#,linq
I write simple query with linq to sql : var query = (from p in behzad.GAPERTitles select new { p.id, p.gaptitle }).ToArray(); up code into the c# windows application ,windows form load event,and i want use up result into the button click event in this scope: private void button1_Click(object sender,...

sqlite query slow, how to optimize (using linq to entities)


c#,linq,entity-framework,sqlite
I have used MS SQL server a few times and have yet to run into a speed issue when querying, using linq to entities. This time, I am using sqlite, as to ship the entire database with the application. I have a winforms app that contains 4 search fields. My...

Using LINQ to reference XML local Xelements


c#,xml,linq
All, It's easy enough to do reference the LocalName of an Element when using a foreach. However, if I'm interested in a particular element name, perhaps because each element has an array of children elements and I want a LocalName of a parental element, how do I go about it,...

Load XML to list using LINQ [duplicate]


c#,xml,linq
This question already has an answer here: XDocument to List of object 1 answer I have following XML: <?xml version="1.0" encoding="utf-8"?> <start> <Current CurrentID="5"> <GeoLocations> <GeoLocation id="1" x="78492.61" y="-80973.03" z="-4403.297"/> <GeoLocation id="2" x="78323.57" y="-81994.98" z="-4385.707"/> <GeoLocation id="3" x="78250.57" y="-81994.98" z="-4385.707"/> </GeoLocations> <Vendors> <Vendor id = "1" x="123456" y="456789" z="0234324"/>...

Finding an item in a list in c#


c#,linq
The code below contains a foreach loop that loops through a list of string collection which contains XML. While enumerating through the collection, it reads the question and answer elements and adds them to the list collection. I need to ensure that no repeated question is added to the list...

Distinct all columns in a datatable and store to another datatable with LINQ


c#,linq
I have a datatable with more than 10 columns and I would like to distinct all columns and then store a result to another datatable. Is there any way to distinct all columns in a datatable by using LINQ without naming all ones? I've tried as the code below but...

Can't access any of Linq methods


linq,asp.net-web-api
I'm writing a simple ApiController for getting product stocks, but I'm having a strange issue. I get the data from a method that returns a System.Linq.IQueryable (In a library), but I can't apply any of the Linq methods, like Count or ToList(). The import directive is present and doesn't report...

Error when building an XDocument


c#,xml,linq,xpath,linq-to-xml
Using the following example xml containing one duplicate: <Persons> <Person> <PersonID>7506</PersonID> <Forename>K</Forename> <Surname>Seddon</Surname> <ChosenName /> <MiddleName /> <LegalSurname /> <Gender>Male</Gender> </Person> <Person> <PersonID>6914</PersonID> <Forename>Clark</Forename> <Surname>Kent</Surname> <ChosenName>Clark</ChosenName> <MiddleName />...

Update list of items in c#


c#,linq,list,updates
I would like to know if you can suggest me an efficient way to update a list of items in c#. Here is a generic example: If CurrentList is [ {Id: 154, Name: "George", Salary: 10 000} {Id: 233, Name: "Alice", Salary: 10 000}] And NewList is [ {Id: 154,...

How can I handle exceptions in Web API 1.0 at my BaseAPIController


.net,asp.net-web-api
I am currently using Web API 1.0 and .NET 4.0 I need a function that can take care of the noise of catching and handling exceptions in my Base API so that I dont need to write that in every RESTful operation. public int Get(WelcomeTeamNotes note) { try { return...

Web API translating input into random int


c#,post,asp.net-web-api,json.net
not sure whether the subject is the best description for this problem but I am getting an unusual problem where I have a single Web API operation and a single field on a request and for some odd reason the value gets manipulated. Depending on the input this gets converted...

How to select rows from a DataTable where a Column value is within a List?


asp.net,.net,vb.net,linq,datatable
Say you had a table in SQL and you wanted to find all the rows where a particular column could be one of 3 options. You could write something like this: SELECT * FROM MyTable WHERE uid IN (123, 456, 789) That's effectively what I want to do with a...

Sort Array by contains specific char count


c#,linq
I have an array and I want to sort this array by its element' specific character count. var myNewArray = myArray.ToList().Sort(u => u.Name.Split(' ').Length); but this does not work at all. How can I provide the LINQ code for this problem ? myArray[0] = "word1 word2" myArray[1] = "word1" myArray[2]...

Group by day, time and id in one LINQ


c#,linq
I have a list of Example class elements: public class Example { public long Id { get; set; } public string Name { get; set; } public DateTime SomeDate { get; set; } } Now I want to group it using ONE LINQ to make the following hierarchy: public class...

Asp.Net Identity find users not in role


asp.net,linq,entity-framework,asp.net-identity
I need to find all users that DONT'T contain a certain role, using Asp.Net Identity. So far I have something like this but it is not working. (From role In context.Roles From userRoles In role.Users Join us In context.Users On us.Id Equals userRoles.UserId Where role.Name <> "SomeRole" Select us.UserName) This...

joining two collections in C# or JavaScript


javascript,c#,linq,collections
I have two objects of "pseudotype" Hash(int key, list values) that I need to combine into one based on the key. For example, [{1, {a, b, c}}, {2, {apple, pear}}, {3, {blue, red}}] and [{2, {tomato}}, {3, {pink, red}}, {4, {x, y, z}}] The result that I need is: [{1,...

Updating entity framework model using Linq


c#,sql,linq,entity-framework
I have a problem with updating data in an entity framework model. I have a few tables in the model (Users, UserActivity and Orders). I have added associations between the tables, one between Users and UserActivity and one between Users and Orders. The associations are through the column UserID. These...

WPF, DataGrid, clicked item/row does not highlight (blue background)


c#,wpf,linq,datagrid
Here is the DataGrid XAML: <DataGrid CanUserAddRows="False" AutoGenerateColumns="False" Height="501" HorizontalAlignment="Left" Margin="6,6,0,0" Name="dataGridTrades" VerticalAlignment="Top" Width="574" SelectionChanged="dataGridTrades_SelectionChanged"> <DataGrid.Columns> <DataGridTextColumn Header="ID" Binding="{Binding TradeID}" IsReadOnly="true"/> <DataGridTextColumn Header="Account" Binding="{Binding AccountName}" IsReadOnly="true"/> <DataGridTextColumn Header="Card Name" Binding="{Binding...

how to parse a rgbColor using c#


c#,linq
I am having trouble parsing a RGB color. I need the int values in there own variable. here is a screenshot of what the object looks like I need to end up with this data [0] R = int value G = int value B = int value Name =...

Linq update with specific select of column being null


c#,linq
I wanted to select few columns from SQl and then update that table. I used var xyz_repl= from mfrepl in xyz_repl_alias where (mfrepl.RPT_ID == sched_data.NOTIF_RPT_ID) && (mfrepl.NOTIF_ID == "" || mfrepl.NOTIF_ID == null) select mfrepl; This did my job but then it does not work if any column is NULL.Then...

What's the best way to map objects into ember model from REST Web API?


json,rest,ember.js,asp.net-web-api,ember-data
The topic of this post is: my solution is too slow for a large query return. I have a Web Api serving REST results like below from a call to localhost:9090/api/invetories?id=1: [ { "inventory_id": "1", "film_id": "1", "store_id": "1", "last_update": "2/15/2006 5:09:17 AM" }, { "inventory_id": "2", "film_id": "1", "store_id":...

Sort a LINQ with another LINQ in MVC


sql-server,linq,entity-framework,controller
Using SQL Server Management Using MVC VS 2013 for Web Being in a Controller Here materialnumb it's a LINQ query that always return only one value. Being the following... var materialnumb = (from r in db.MaterialNumber where r.MaterialNumber == 80254842 select r.MaterialNumber); I have another LINQ query from a...

Convert delimited string to array and group using LINQ in C#


c#,arrays,linq,csv
I have a string that has a delimited format like this: orgname: firstname lastname, firstname lastname; (this can repeat with orgnames and variable number of names for each org) Example: **XXX University**: Martha Zander, Rick Anderson; **Albert School**: Nancy Vanderburg, Eric Towson, George Branson; **Hallowed Halls**: Jane Goodall, Ann Crabtree,...

check if a list contains all the element in an array using linq


vb.net,linq
I have a list of objects and I have an array of keywords. I need to check if all the elements of the array are present inside the list of objects. The user enters the data to be searched like this pain+fever+thirst+itching My code looks like: //i check if the...

Listing directories by content size using C# [closed]


c#,.net,windows,linq
I'm trying to list all folders of my c drive excluding the document folder which i do not seem to have access to. This first seemed rather simple to me but i found myself still struggling with it despite the seemingly rich .net library. I can't post any code as...

How does the Take() method work in LINQ


c#,.net,linq,entity-framework
I have a question regarding LINQ's Take() Method. I have a somewhat large table I'm querying in my web app, and I only want to return say N number of rows from the table. I've read through the MSDN documentation, but I can't see where it states if Take() first...

Adding where clause to IEnumerable Select


c#,asp.net-mvc,linq
I have the following line of code in my controller that selects the id's of the interests shown within a view (they are listed down the page). IEnumerable<int> interestIds = viewModel.ExistingInterests.Select(x => x.InterestId); However I want to be able to add a where clause to the select section. In ExisitingInterests...

Linq where clause with if condition


c#,linq
I have the following model: class Project{ bool IsDeleted {set;get;} ICollection<Document> Documents {set;get;} } class Document{ Project Project {set;get;} int? ProjectId {set;get;} } I am querying Document repository, I want to get all the documents and also the documents whose project is not deleted. var documents = _repository.Include(p=>p.Project) .Where(m =>...

LINQ to Entities Retrieving related Entities or T-SQL


c#,sql-server,linq
I have these (simplified) models: class Vendor { public int Id { get; set; } public IEnumerable<Product> Products { get; set; } public IEnumerable<Booth> Booths { get; set; } } class Show { public int Id { get; set; } public IEnumerable<Booth> Booths { get; set; } } class Booth...

How to select all objects that have a property value in list of values?


c#,linq,linq-to-entities
I have a table named Items. Items have a property named "locationId" Given a list of location Ids, how do I select all items? List example List<long> locationIds = new List<long> { 1, 2, 3 }; Essentially the query below, but for multiple locations at once: var sleectedItems= db.Items.Select(i =>...

how can I add a column to IQueryable object and modify its values


c#,.net,linq,grid,devexpress
var packs = from r in new XPQuery<Roll>(session) select new { Number = r.number Selection = new bool() }; gcPack.DataSource = packs; I want to add another column to my grid control with: Selection = new bool(). It will be added to the grid but I can't change its...

ExecuteQuery returns empty collection when there is only a single result


c#,sql-server,linq
I'm using a auto created Linq to SQL Classes dbml and I have created the model class by hand. It should select all Schemas from a SQL Server, which is working when there are more than one Schema in the Database, but when there is only a single result I...

Route parameter with slash “/” in URL


asp.net-web-api,routing,asp.net-web-api2,asp.net-web-api-routing,attributerouting
I know you can apply a wildcard in the route attribute to allow / such as date input for example: [Route("orders/{*orderdate}")] The problem with wildcard is only applicable to the last paramter in URI. How do I solve the issue if want to have the following URI: [Route("orders/{orderdate}/customers")] ? EDIT:...

Compare if the characters in a string are a subset of a second string in C#


c#,linq,string-comparison
I'm working on a game where I want to check if the characters of a string are contained in another string. Obviously a set would be my first choice but I want to account for duplicates. For example: "met".IsContainedWithin("meet"); => true "meet".IsContainedWithin("met"); => false A multi-set would be nice but...

How do I convert this tSQL statement to LINQ using group by in a sub query


c#,sql-server,linq,tsql
I have the following MSSQL query I am trying to convert to LINQ. I am using entity framework with the following syntax to get at the data. var rv = (from i in DC.TableA select i).ToList(); This is the sql I want to write a C# LINQ query for but...

Cannot read property 'client' of undefined using SignalR


asp.net-web-api,signalr,signalr-hub
I've been working all day on this with no luck. I have also tried (almost) every single SO question, but I didn't get it to work... I'm running web api with very simple SignalR push message and separately simple front end to show this push message. In my case the...

How can I select items where there exists a reference between each item and all items in a list?


c#,linq
I have a list of objects called Keywords, each with an Id. In my database, I have a table of Forms and a table of KeywordReferences. Each KeywordReference has a FormId and a KeywordId. What I need to do is create a query that gets all Forms where there exists...

DataTables Warning: Requested unknown parameter 'pCodigo' for row 0


asp.net-web-api,datatables
I'm trying to populate a table on a button click, getting the data from an ASP.NET ApiController. I've tried with almost all solutions posted in SO to other similar issues but always get that error. Hope someone sees the problem. The html markup: <input type="button" ID="btnSearch" name="btnSearch" class="btn btn-success" value="Buscar"...

CSV File header part is coming parsing by LINQ


c#,linq,csv
the below way i am parsing csv file by LINQ but i found header part is coming when i inspect user class data. what is wrong there in code. var csvlines = File.ReadAllLines(filename); // IEnumerable<string> var csvLinesData = csvlines.Select(l => l.Split(',').Skip(1).ToArray()); // IEnumerable<string[]> int flag = 0; var users =...

Get List of Elements in Tree with specific Field Value


vb.net,linq,properties,interface
I have an Interface like this: Public Interface TreeSelectorAttributes Property selectedInTreeSelector As Boolean Property Name As String ReadOnly Property childs As IEnumerable(Of TreeSelectorAttributes) End Interface and I have a TreeView which has a List of this TreeSelectorAttributes: Public Property rootList As IEnumerable(Of TreeSelectorAttributes) now after the User chooses which elements...