LINQ Range Variable Problem
Ran into this issue last night and just figured it out. I have this code for a demo:
using System;
using System.Data.Objects;
using System.Transactions;
using ExtractTransformLoad.Domain;
using Northwind.Entities;
//using System.Linq;
namespace ExtractTransformLoad
{
public class SqlFreightByShipperRepository : IFreightByShipperRepository
{
public void DeleteAndInsert(DateTime runDate, FreightByShipper freightByShipper)
{
using (var context = new NorthwindEntities())
using (var scope = new TransactionScope())
{
var summaryToDelete = (from freightSummary in context.FreightSummaries
where
freightSummary.RunDate == runDate &&
freightSummary.ShipperName == freightByShipper.ShipperName
select freightSummary);//.FirstOrDefault();
context.DeleteObject(summaryToDelete);
var newFreightSummary = new FreightSummary()
{
Freight = freightByShipper.Freight,
RunDate = DateTime.Today,
ShipperName = freightByShipper.ShipperName
};
context.FreightSummaries.AddObject(newFreightSummary);
context.SaveChanges(SaveOptions.AcceptAllChangesAfterSave);
scope.Complete();
}
}
}
}
Now, in Visual Studio, it looks like this:
Hovering over freightSummary in the above LINQ query would reveal just
(range variable) ? freightSummary
A bunch of searching later didn’t much help, although this thread did put me on the right track just a moment ago. The trick, it turns out, is that I didn’t have the System.Linq namespace included (you can see above I just re-commented it out). If you include System.Linq, everything works as expected. Final code here:
using System;
using System.Data.Objects;
using System.Transactions;
using ExtractTransformLoad.Domain;
using Northwind.Entities;
using System.Linq;
namespace ExtractTransformLoad
{
public class SqlFreightByShipperRepository : IFreightByShipperRepository
{
public void DeleteAndInsert(DateTime runDate, FreightByShipper freightByShipper)
{
using (var context = new NorthwindEntities())
using (var scope = new TransactionScope())
{
var summaryToDelete = (from freightSummary in context.FreightSummaries
where
freightSummary.RunDate == runDate &&
freightSummary.ShipperName == freightByShipper.ShipperName
select freightSummary).FirstOrDefault();
context.DeleteObject(summaryToDelete);
var newFreightSummary = new FreightSummary()
{
Freight = freightByShipper.Freight,
RunDate = DateTime.Today,
ShipperName = freightByShipper.ShipperName
};
context.FreightSummaries.AddObject(newFreightSummary);
context.SaveChanges(SaveOptions.AcceptAllChangesAfterSave);
scope.Complete();
}
}
}
}
I guess I’m spoiled by Resharper, which normally prompts me for any namespace it detects that I’m trying to use but haven’t yet included. It wasn’t until I added the .FirstOrDefault() that R# kicked in, and then for some reason it couldn’t automatically add the using statement for System.Linq, but once I did so by hand, the Range Variable problem disappeared.