.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
Gaurav Pal
Post New Web Links

Linq return type as integer

Posted By:      Posted Date: October 11, 2010    Points: 0   Category :ASP.Net


var pagemodelid = from pageModel in pageList
                     where pageModel.PageOrder == 2
                     select pageModel.Id;

This query returns a integer but I have to store it to var. It will be nice if I could do like this

int pagemodelid = from pageModel in pageList
                     where pageModel.PageOrder == 2
                     select pageModel.Id;

But it shows a error.

Is there any way to have integer in return type for linq query ?



View Complete Post

More Related Resource Links

Need Syntax To Make Results of LINQ Union Return Non-Generic Type



I have the below SQL which works just fine:

SELECT     Message, CreateDate, AccountId, AlertTypeId
FROM       dbo.Alerts
SELECT     TOP (100) PERCENT Status, CreateDate, AccountId,
                          (SELECT     10 AS Expr1) AS AlertTypeId
FROM         dbo.StatusUpdates
WHERE AccountId = PassedInParameter

I have been going about trying to convert the above into a LINQ method and am having problems with return types.
As the above SQL illustrates, I am querying two distinct LINQ tables - Alerts and StatusUpdates -
and then attempting to perform a Union on them. In order to do the union in LINQ, I have to have agreeing types. So, I
am using "var" to make the results of "alerts" and "updates" generic before the union.  

public IList GetStatusUpdatesAsAlertsByAccountId<T>(Int32 accountId)
            using (WorkbookDataContext dc = _conn.GetCont

No Return Type for a Stored Procedure in a Linq to SQL Data Layer

Hello. First, I don't know if this is the right forum section to post this in, but I couldn't fine a more suitable one. Feel free to move this if it's totally worng. I have a weird problem when using LINQ to SQL and Store Procedures with a return value... The problem is that when I drag my SP's onto the "Methods Pane" the property field "Return Type" is set to (None) and greyed out. And here's the most weird thing... I created a test SP yesterday wich returned SCOPE_IDENTITY() and it worked flawlessly. Dragged it onto the "Methods Pane", could play with the return type property (hence it was not greyed out) and everything was working out nice. I used a ISingleResult<T> and could fetch the .ReturnValue... Today I was going to contiune to create the rest of the SP's i needed with a return type but today when I drag my Store Procedures to my Methods Pane, I couldn't access the Return Type property... I even dragged the SAME procedure I used yesterday (wich then worked great) and now I can't get the dbml-layer to notice that there is a return value... I've tried to create new solutions, new Data Layers, used different databases/servers, but still the same problem... Don't really know if it's LINQ or something else that's causing this... This is how part of my SP wich I used yesterday to test looks

Return type of Linq to SQL Stored Procedures


Dear all,

I am using .net framework 3.5 and sql server 2008.

In my project coding, I want to call stored procedures in sql server 2008.

return value is the object list which references the entity.

But I have the questions.

If in the entity named as "order", is it matching the properties or created through entity constructor??

In my case, I have two properties and one constructor which match one property.

public class orders


orders ( string orderid)




public string orderid {get;set;}

public string orderno{get;set;}

The type 'System.Data.Linq.DataContext' is defined in an assembly that is not referenced. You must



This is frustrating, and I don't know how to solve it.

I have a strange problem. I am adding a LinqDatasource object, and set the context:

        protected void LinqDataSource_ContextCreating(object sender, LinqDataSourceContextEventArgs e)
            e.ObjectInstance = new KaruselaDataContext(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);

Then I get this error:
The type 'System.Data.Linq.DataContext' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Data.Linq, Version=, Culture=neutral, PublicKeyToken=b77a5c561934e089'.


On web.config I already have this:
<add assembly="System.Data.Linq, Version=, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>

NOTE: The datacontext is in a different project (DLL proect) where I added a refernce to System.Data.Linq.

is there another way adding a refernce to a web project? or only though teh web.config?


linq and max, if return null return error


hi there
i have this query :

var result2 = (from TH in DB.Threshold
                          where TH.ProductSKUID == int.Parse(HID_ProductSKUID.Value)
                          select TH.ThresholdID).Max();

the problem is that if this query does not find any items, return null, so thow exception
how can i do to return 0??

Linq join fields for return data


  how would I join fields together?

           return (from c in storedb.Product_Categories

                         where c.Category_Name.Contains(searchText)
                         orderby c.Category_Name
                         select new {
                                    c.Category_Key && " ;" && c.Category_Name // HOW CAN I DO THIS.....

Linq to sql does not return appropriate multiple result sets with "If exists" conditions in the stor


Hello All,

I have a stored proc that returns 4 resultsets, they are in the format.

ALTER PROCEDURE [dbo].[pGetManagerEmployeeSummaryDummy]

    @ManagerStaffID int,
    @PeriodID int



IF EXISTS (select 1 from dbo.temployee e
    inner join dbo.temployeedetail ed
        on e.staffindividualid = ed.staffindividualid
        and ed.periodid = @PeriodID  
    inner join Incentive.tRole r
        on rm.IncentiveRoleID = r.RoleID
    where ed.ManagerIndividualStaffID = @ManagerStaffID
    AND r.RoleID = 1) --Closer
        SELECT e.StaffIndividualID, e.LastName, e.FirstName, r.RoleName, e.xname, e.yname

from dbo.temployee e

inner join dbo.temployeedetail ed
            on e.staffindividualid = ed.staffindividualid
            and ed.periodid = @PeriodID

where ed.ManagerIndividualStaffID = @ManagerStaffID

Check if Linq query return result

HelloI have Linq query likeDim Prood= (From p InProdutcts _                                          where p.ProductID="InputInteger"                                                         ..... ) .SingleOrDefaultI could Use Count if I Use .ToList Instead of .SingleOrDefault , But now that I use 'SingleOrDefault', how Could I find if Prod contains any record or it's Empty.

The type or namespace name 'Linq' does not exist in the namespace 'System'

Hi, I uploaded my website to the server, and I have there a working with wcf - it should be fw 3.5 I saw that fw 3.5 is installed on the server and also we have there fw 3.0 sp1. I run my website : www.qenglishcenter.com and I'm getting an error : The type or namespace name 'Linq' does not exist in the namespace 'System' (are you missing an assembly reference?) shouldn't System.linq be already existed ? Thanks for any reply.  

SQL data type for HL7 message retaining carriage return and new line characters

Hi, What data type should be used for a column storing text as descripted in title? Please advise. I crrently have the message stored as text, but if I copy the message from studio management to a notepad, it will be come one big line of text instead.  

Return linq query in function

I try to return a var query from a function, but i'll get the error: Error:Error 41 Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<AnonymousType#1>' to 'System.Collections.Generic.IEnumerable<System.Xml.XmlElement>'. An explicit conversion exists (are you missing a cast?)  Code: protected static IEnumerable<XmlElement> GetModels(byte MerkID) { string rawXML = AutoDisk.GetModels(12345, true, MerkID, "2010", ""); XmlDocument xml = new XmlDocument(); xml.LoadXml(rawXML); var query = from feed in xml.DocumentElement.ChildNodes.Cast<XmlNode>() select new { nModelID = feed.SelectSingleNode("nModelID").InnerText, Modelnaam = feed.SelectSingleNode("Modelnaam").InnerText }; return query; } Whats wrong and how can i make this working ?  

How to use return JSON object from web service as a declared Type?

Hi, I just hit the following issue: I am calling a web service that returns a serialized JSON object let's say: __type, FirstName, LastName (.net object Person with properties FirstName and LastName). __type's value is Test.Person I have created a JS object using Type.registerNameSpace/registerClass called Demo.Person and it is registered on the page using the ScriptManager. Everything is working fine; I am able to get data from the server on the call back. Is it possible to make the returned object from the web service be an instance of the declared JavaScript Demo.Person class? The idea would be to call a method like result.getFullName() on the client side without having to copy all the properties. This is just a simple scenario for more complex objects.   Thanks,   Teo

Linq to SQL with XML data type

Hi guys, I need your help.  I am having some issues updating sql table with Linq to Sql dataContext objects.  When I call SubmitChanges with modifications to the data, the simple types (int, varchar) get updated, but I also have an XML data type and this does not get updated.  Below is a sample of my code to update an existing record.                   Dim db As New EnrollmentDataClassesDataContext(True)                                                 Dim orderIdGuid As New Guid("9EA26E39-07F1-4C1F-B7CD-B6D323DF9D70")                Dim orderDetailEntity As OrderDetail                orderDetailEntity = (From checkout In db.OrderDetails Where checkout.OrderId = orderIdGuid Select checkout).SingleOrDefault                If Not orderDetailEntity Is Nothing Then          

ListData.svc fails if list has calculated column with Yes/No (boolean) return type


I have a list with a calculated column whose return type is Yes/No.  If I try to browse to the list or a list item using REST via ListData.svc, I get the error "An error occurred while processing this request".  Can't seem to find anything in 14\LOGS or the System or Application event logs.  I've tried multiple calculation formulas such as:



Both display "Yes" when viewing through the SharePoint UI and are sortable and filterable.  If I change the calculated column return type to anything else (single line of text, currency, date/time, etc.) and update the formula as necessary, ListData.svc displays the list item XML as expected.  If I replace the calculated column with a regular column whose type is Yes/No, ListData.svc displays the list item XML as expected.

Is this a known bug?  Is there a workaround (other than manually casting to bool in my code)?

how to return linq result to dataset



        i have one class which return dataset  as a returnvalue. i write stored procedure and calling that stored procedure uding linq thsts work but after calling i want linq result must store in dataset and then i return that dataset like

 public DataSet GetData(int id)
        DataSet dsInc = new DataSet();
        AdministratorDataContext db = new AdministratorDataContext();

        var result = db.StoredProcedure1(id);

return dsInc


so i want to return dsInc i.e dataset but how i stored that result in my dataset. Reply me ASAp.

how to do databinding with linq so it understands the data type

var connstr = "Server=localhost:27017";

      mongo = new Mongo(connstr);
      IMongoDatabase TorontoTrader = mongo["TorontoTrader"];
      IMongoCollection TradingStrategyCollection = TorontoTrader["TradingStrategyRefresher"];
      IEnumerable<Document> docs = from doc in TradingStrategyCollection.Linq()
            where (int)doc["TriggerBarId"] == 102
            select doc;

      dataGridView1.DataSource = docs.First().ToList();


Now this binds my data to my datagrid. however how can i map it so that if i get a Int datatype, it creates a editable textbox on the datagrid. 

any ideas would be very helpful to me.


Value of type 'Integer' cannot be converted to 'System.IntPtr'


I am receiving an error with a line of code I have learnt from a tutorials site (after converting it from C# to VB):

Dim thumb As System.Drawing.Image = image.GetThumbnailImage(CInt(Math.Truncate(imgWidth)), CInt(Math.Truncate(imgHeight)), Function() False, DirectCast(0, IntPtr))

The error relates to the "IntPtr" part, and reads:

"Value of type 'Integer' cannot be converted to 'System.IntPtr'"

Strangely, when this code was contained in a different class, there was no issue with it! I have imported the following:

Imports System.Collections
Imports System.Collections.Specialized
Imports System.Configuration
Imports System.Text
Imports System.Text.RegularExpressions
Imports System.Web
Imports System.Web.Caching
Imports System.Web.SessionState
Imports System.Web.Security
Imports System.Web.Profile
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts
Imports System.Web.UI.HtmlControls

Any ideas?

ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend