.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 "connection is closed..." issue

Posted By:      Posted Date: April 14, 2011    Points: 0   Category :ASP.Net


I am having trouble navigating through the forums to locate a LINQ forum so I am posting here.  Please excuse my error if this is incorrect.  I have been using LINQ for about 2 years and have not encountered this problem before.  Reference the attached snippet.  Note that during execution of the "foreach" loop, in the debugger at least, an error, "...connection is closed..." is thrown.  I suspect that I am making a stupid mistake but cannot locate it.  Oh, I am using VS2010 and C#. 

View Complete Post

More Related Resource Links

Compile issue with List<> and Linq

I am pretty sure this is some framework version issue but I am getting this on a (custom layout) page compile migrated over from MOSS. The following code complies in my MOSS 2007 environment but does not in my new 2010 environment. Thanks in advance for any help. Code section #1: private bool isSuccessReturnCode(string s) { bool bReturn = false; // Following line fails looking for ';' XDocument loaded = XDocument.Parse(s); var q = from c in loaded.Descendants("Node") select (string)c.Element("ReturnCode");   Code Section #2 private InvoiceItem getInvoiceItem(Guid ID) { List<InvoiceItem> InvoiceItems = ((List<InvoiceItem>)ViewState["INVOICEITEMS"]);

Linq forward compatibility issue

In Linq 3.5 I used to be able to do this, but the code in bold is no longer compatible in Linq 4.0, Is there another way to declare the query variable prior to assigning it (PLEASE DO NOT SUGGEST TO DECLARE AS VAR, IT DOES NOT WORK AND CAN NOT BE DECLARED AS NULL):   ProjectArtifactsDataContext dbProjectAttributes = new ProjectArtifactsDataContext();IQueryable<ProjectArtifacts.Defect> query1 = null;   This type of declaration allowed me to create aggregate and complex queries such as         if (UserControlHost.ShowMyItemsOnly)        {            Guid currentUserId = (Guid)Membership.GetUser(Membership.GetUser().UserName).ProviderUserKey;            query1 = dbProjectAttributes.Defects.Where(defect =>                 defect.Active == true && defect.AssignedTo == currentUserId);        }         else        {            if (FilterInactive == true)                que

LINQ to SQL Compact db, file copy issue

Our application uses LINQ and SQL compact database .sdf file as datasource.  It is using Miscrosoft SQL Server Compact 3.5 SP 1 and .NET Framework 3.5 SP1. We store our application's project data into a .sdf file.  When our application opens a .sdf file (e.g. projectA.sdf), it will make a temporary copy of it and open the temporary file instead of the original file.  If we change one table cell value (i.e. one property value of an object that is created by LINQ), and call DataContext.SubmitChanges(ConflictMode.ContinueOnConflict), and then call File.Copy(DataContext.Connection.Database, filename, true); to copy the temporary file back to the original file (replacing the original one).   We found that the table value is not changed in projectA.sdf.  But in the temporary copy, the value is changed.  If we re-open db connection by calling DataContext.Connection.Close(); DataContext.Connection.Open(); right before calling File.Copy(), the changed value is copied successfully to projectA.sdf. If we do a lot of value changes in the database, or adding / deleting table row, then submit changes.  Without re-opening the db connection, after File.Copy(), the projectA.sdf have those changes copied. This strange behaviour looks like the temporary db file is cached.  For a small change, the cached version is not changed.  The File.Copy() use t

LINQ to SQL Classes (dbml file) across multiple websites issue



I have a single LINQ to SQL Classes (dbml file) compiled in a Class Library that's referenced by 3 websites. Inside that Class Library there's also a class that's using the DBML to manipulate data.

At one point it needs to save in a user table the user info (firstname, lastname, email). SOMEHOW (!?) two of the 3 webapps saves email instead of firstname and viceversa while the other 1 saves them correctly ! The one compiled last seems to be the one saving correctly.

There's no code error as I have debugged this multiple times. The values are assigned correctly but before the SubmitChanges() call the data inside the database object is corrupted.

Now, I have already fixed this locally by putting every website in a separate AppPool (which also needs to be set to "Classic" and not "Integrated". However I really don't want to bug the client with such IIS changes so I'm looking for another workaround !

Please Help!



Linq to Entities Many to Many Persistence Issue


I am having problems persisting a many to many. My code saves the Problem but not the users that can be attached to a problem. My Linq to Entities Mapping is below in the first three code blocks. I then have my ASP MVC controller method which receives a problem, a file (optional), and a string array of users which are allowed to view the problem. I retrieve the Users from the UserRepository and add them to a List which is then passed through to the ProblemRespository with the problem and added to the problem.Users collection. However when submitted only the problem is being saved and not the records which are required in the junction table. Any help would be appreciated. This is the first time I've attempted my own mapping.
Thanks in advance.

Linq Float/Double Issue


I'm using linq to sql, and everything seems to be working fine except one thing, I'm showing any mapped float fields from my db tables as "Double?" instead of "Double", and when binding to a datagrid, any of those "Double?" fields don't show.

If I iterate through the items and spit out the property, the float value is indeed there and properly returned.  What's going on here?

LINQ To SharePoint - SPMetal Issue


Hi All,

We an issue with LINQ to SharePoint in creating entities class. Whenever i created the entities class using SPMetal, one or more columns are automatically created in RemoveColumnAttribute something as shown below.

    public override string Status
        throw new System.InvalidOperationException("Field WorkflowPRStatus was removed from content type.");
        throw new System.InvalidOperationException("Field WorkflowPRStatus was removed from content type ");

Could anyone faced this issue and how to get rid of this Remove


Any suggestions are welcome.


Chandrasekaran C N

Chandrasekaran C N

LINQ to XML Query Issue



I wanted to retreive "Summary" attribute from following XML using LINQ to XML. Contract and Cancellation fee are working fine. Getting issue in discount. help will be  appreciated.

 var res = from feed in doc.Descendants("pp")
          where feed.Attribute("code").Value == "XYZ-ABC-00"
         select new


            Con_Summary = feed.Element("contract_term").Attribute("Summary").Value,

            Can_Summary = feed.Element("cancellation_fees").Element("cancellation").Attribute("Summary").Value,

            Dis_Summary = feed.Element("discounts")



<pp code="XYZ-ABC-00" >

    <fuel_types elec="true" gas="true" dualOnly="false" />

    <contract_term period="months" Summary="3 Year Contract">36</contract_term>

system.linq.enumerable.where Issue



I have a table "OSTAN" with two columns "ID" (Key index) and "NAME". I am trying to  construct a linq query to select the Name for a specific ID. I have not luck trying to construct the where clause. Here what I have so far:


using (XeledsEntities db = new XeledsEntities())
            string SelectedName = db.Ostans.Name.Where( Ostan=> Ostan.Equals(Request.QueryString["Ostan"])).FirstOrDefault(); 


Can anybody help me construct this where clause to set the Selected Name?

Playing with Linq grouping: GroupByMany?

One of its features is grouping. Many people understand grouping like it is defined in Sql. Linq is implementing grouping quite the same way. Let's discover this syntax and how to make consecutive groups easier.

LINQ : Implementing IN and NOT IN

I got tried of typing

var result = from s in source
where items.Contains(s)
select s;and so I implemented the IN and NOT IN methods as extension methods:

101 LINQ Samples Tutorials

101 LINQ Example with sample code snippets....This sample prints each element of an input integer array whose value is less than 5. The sample uses a query expression to create a new sequence of integers and then iterates over each element in the sequence, printing its value

Linq: how to share parameters between lambda expressions ?

When using Linq to objects, you will quickly feel the need to pass some parameters from a method to another but it's not so easy because each Linq method is not calling the following one. In a Linq sequence, each method is using the result computed by the previous one. So, local contexts are not visible from one method to another.
The compiler is using two technical different ways to let parameters go out of a method.

Linq to Sql CompiledQuery container

Ok now let's go. Here is just a little trick but with some interesting patterns that could be useful in some other contexts not connected to Linq to Sql.

When using Linq expressions, like with Linq to Sql, translating the expression into something else (sql for example) is taking time and resources. Sometimes it's negligible, sometimes not...

LINQ to SQL Paging using GridView in C# and ASP.NET 3.5

This tutorial will show you how we can extend the LINQ to SQL Class and create methods that will allow us to page data from a SQL database. C# version.

What is Lambda Expressions In LINQ

A lambda expression is an anonymous function that can contain expressions and statements, and can be used to create delegates or expression tree types.

All lambda expressions use the lambda operator =>, which is read as "goes to". The left side of the lambda operator specifies the input parameters (if any) and the right side holds the expression or statement block. The lambda expression x => x * x is read "x goes to x times x." This expression can be assigned to a delegate type as follows:

How to create 3 tier application using LINQ

As you know that in 3 tier architecture there are three layers

User interface layer. (Is our Form in Windows application and .aspx page in Web application)
Data Access layer. (Which provides interface between Business logic layer and Database)
Business Logic layer.(Which stores your application logic)
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