Lucie
Lucie

Reputation: 161

.NET Already Open DataReader

I get this error when running this code. I have looked for solution though I don't like the idea of using MARS as people have suggested as it may contain a lot of data, is there any other option here? Also can I edit a variable in a database without rewriting all of them as I do here, will this save server power or make no difference?

There is already an open DataReader associated with this Command which must be closed first.

    public ActionResult CheckLinks(Link model)
    {
        var userId = User.Identity.GetUserId();
        var UserTableID = db.UserTables.Where(c => c.ApplicationUserId == userId).First().ID;
        foreach (var item in db.Links.Where(p => p.UserTable.ID == UserTableID))
        {
            string pageContent = null;

            HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(item.Obdomain);
            HttpWebResponse myres = (HttpWebResponse)myReq.GetResponse();

            using (StreamReader sr = new StreamReader(myres.GetResponseStream()))
            {
                pageContent = sr.ReadToEnd();
            }
            string live = "";
            if (pageContent.Contains(item.Obpage))
            {
                live = "Yes";
            }
            else { live = "No"; }

            var link = new Link { Obdomain = item.Obdomain, ClientID = item.ClientID, Obpage = item.Obpage, BuildDate = item.BuildDate, Anchor = item.Anchor, IdentifierID = item.IdentifierID, live = (Link.Live)Enum.Parse(typeof(Link.Live), live), UserTableID = item.UserTableID };
            db.Entry(link).State = EntityState.Modified;
            db.SaveChanges();
        }
        return RedirectToAction("Index");
    }

Upvotes: 1

Views: 79

Answers (1)

fatherOfWine
fatherOfWine

Reputation: 1251

Entity Framework allows only one active command per context at a time. You should add .ToList() at the end of the following statement:

db.Links.Where(p => p.UserTable.ID == UserTableID).ToList();

So your code could look like this:

var items = db.Links.Where(p => p.UserTable.ID == UserTableID).ToList();
foreach (var item in items)

Upvotes: 2

Related Questions