Read from CellSet using LINQ - linq

AdomdCommand cmd = new AdomdCommand(commandText, conn);
CellSet cs = cmd.ExecuteCellSet();
var result = from a in cs
select new
{...};
Is it possible to use LINQ to read from CellSet? I have tried using DataTable instead of CellSet but it's much slower (Example: I took a query that using DataTable takes ~45 sec to execute, but using CellSet it takes ~5 sec).
The error I get when trying to use LINQ:
Could not find an implementation of the query pattern for source type
'Microsoft.AnalysisServices.AdomdClient.CellSet'. 'Select' not found.
UPDATE:
I have tried Enrico's suggestion and so far it doesn't return any errors. Next problem is how to read a value from a cell. Here's what I have tried so far:
var result = from cell in cs.Cells.Cast<Cell>()
select new searchResultsPolicy
{
PolicyNumber = ...
InsuredName = cell.Field<string>("[Insured].[DBA Name].[DBA Name].[MEMBER_CAPTION]"),
Agency = cell.Field<string>("[Agency].[Agency Name].[Agency Name].[MEMBER_CAPTION]"),
Market = cell.Field<string>("[Market].[Market Name].[Market Name].[MEMBER_CAPTION]"),
Revenue = String.Format("{0:#,##0}", cell.Field<double?>("[Measures].[Revenue]") ?? 0),
Premium = String.Format("{0:#,##0}", cell.Field<double?>("[Measures].[Premium]") ?? 0)
};

The reason you get that error is that the CellSet class in itself doesn't implement IEnumerable<T>, which is required by LINQ.
Try executing the LINQ query over the CellSet.Cells property instead. That will return a CellCollection object, which implements IEnumerable. From there you can easily convert it to an IEnumerable<T> by using the Enumerable.Cast<T> method.
AdomdCommand cmd = new AdomdCommand(commandText, conn);
CellSet cs = cmd.ExecuteCellSet();
var result = from cell in cs.Cells.Cast<Cell>()
select new
{ ... };
See also:
Retrieving Data Using the CellSet

Related

I need most complicated query

I use Linq to Sql.
I have three table.
tabl_Region: from this table returning .ToList() via county column == 85
tabl_Season: from this table returning .ToList() via startdate >= today
tabl_Desc: from this table returning int [] ID via fldRegion== 1 results && fldSeason== 2 results
I will try to explain not worked codes
TurkusEntities context = new TurkusEntities();
return context.tabl_AttrDesc.Where(c => c.fldRegionId == context.tabl_Region.Where(r => r.fldCounty == 85).ToList() && c.fldSeasonId == context.tabl_Season.Where(s => s.fldStartDate >= DateTime.Now).ToList()).ToList;
I know i can solve it by using loops, but if it is possible i want to use only query.
If you are using Linq2Sql you can get the
sql that is generated by a linq query. with this command.
dc.GetCommand(query).CommandText
If you are using SQL Server Profiler inside the Sql Server (Tools --> SQL Server Profiler)
I found solution but not impossible in one query.
First I got int [] ID arrays which match conditions from two tables.After I wrote a query which provide control column data from arrays.
TurkusEntities context = new TurkusEntities();
Region region = new Region();
string[] dataarray = region.GetAllRegionsBySomeRule(RegionX);
var _db= context.tabl_AttrDesc.Where(c =>dataarray.Contains(c.fldRegionId.ToString().Trim())).ToList();
And Region
public string[] GetAllRegionsBySomeRule(int fldType,int fldRegionX)
{
TurkusEntities context = new TurkusEntities();
var _db = context.tabl_Region.Where(c => c.fldTown.Contains(fldRegionX.ToString())).ToList();
foreach (var data in _db)
{
Regions.Add(data.fldId.ToString().Trim());
}
string[] IDS = Regions.ToArray();
return IDS;
}

SPFieldLookupValue in Linq Query

I'm trying to the the value of a lookup field in SharePoint using Linq and a collection of SPListItem - something like this:
int totalDepts = (from SPListItem itm in hourEntries select ((SPFieldLookupValue)itm["Level1"]).LookupValue).Distinct().Count();
But that doesn't seem to work (and it strikes me as missing some steps)
Has anyone done this before?
I wasn't able to figure out to do it directly in the Linq query, so I ended up creating WorkHoursEntries object, and populating it with all my SPListItems
List<WorkHourEntry> workHourEntries = new List<WorkHourEntry>();
foreach (SPListItem hourEntry in hourItems)
{
//Collect entries that are in the current Fiscal Year reporting period
if (fiscalYearMonths.Contains(hourEntry["Reporting_x0020_Month"].ToString()))
{
WorkHourEntry curEntry = new WorkHourEntry();
string Level1 = (string)hourEntry["Level1"];
SPFieldLookupValue val = new SPFieldLookupValue(Level1);
curEntry.organization = val.LookupValue;
SPFieldCalculated cf = (SPFieldCalculated)hourEntry.Fields["WECSCHours"];
curEntry.WECSCHours = cf.GetFieldValueForEdit(hourEntry["WECSCHours"]);
workHourEntries.Add(curEntry);
}
}
This allowed me to run Linq queries directly on the WorkHourEntry collection
var uniqueDeptNames = (from itm in workHourEntries select itm.organization).Distinct().ToArray();

Multiple rows update without select

An old question for Linq 2 Entities. I'm just asking it again, in case someone has came up with the solution.
I want to perform query that does this:
UPDATE dbo.Products WHERE Category = 1 SET Category = 5
And I want to do it with Entity Framework 4.3.1.
This is just an example, I have a tons of records I just want 1 column to change value, nothing else. Loading to DbContext with Where(...).Select(...), changing all elements, and then saving with SaveChanges() does not work well for me.
Should I stick with ExecuteCommand and send direct query as it is written above (of course make it reusable) or is there another nice way to do it from Linq 2 Entities / Fluent.
Thanks!
What you are describing isnt actually possible with Entity Framework. You have a few options,
You can write it as a string and execute it via EF with .ExecuteSqlCommand (on the context)
You can use something like Entity Framework Extended (however from what ive seen this doesnt have great performance)
You can update an entity without first fetching it from db like below
using (var context = new DBContext())
{
context.YourEntitySet.Attach(yourExistingEntity);
// Update fields
context.SaveChanges();
}
If you have set-based operations, then SQL is better suited than EF.
So, yes - in this case you should stick with ExecuteCommand.
I don't know if this suits you but you can try creating a stored procedure that will perform the update and then add that procedure to your model as a function import. Then you can perform the update in a single database call:
using(var dc = new YourDataContext())
{
dc.UpdateProductsCategory(1, 5);
}
where UpdateProductsCategory would be the name of the imported stored procedure.
Yes, ExecuteCommand() is definitely the way to do it without fetching all the rows' data and letting ChangeTracker sort it out. Just to provide an example:
Will result in all rows being fetched and an update performed for each row changed:
using (YourDBContext yourDB = new YourDBContext()) {
yourDB.Products.Where(p => p.Category = 1).ToList().ForEach(p => p.Category = 5);
yourDB.SaveChanges();
}
Just a single update:
using (YourDBContext yourDB = new YourDBContext()) {
var sql = "UPDATE dbo.Products WHERE Category = #oldcategory SET Category = #newcategory";
var oldcp = new SqlParameter { ParameterName = "oldcategory", DbType = DbType.Int32, Value = 1 };
var newcp = new SqlParameter { ParameterName = "newcategory", DbType = DbType.Int32, Value = 5 };
yourDB.Database.ExecuteSqlCommand(sql, oldcp, newcp);
}

Subsonic Syntax Question (with GroupBy)

Is there a way to do this :
SubSonic.Where filter = new SubSonic.Where();
filter.ColumnName = Region.Columns.Region;
filter.Comparison = SubSonic.Comparison.IsNot;
filter.ParameterValue = null;
SubSonic.Aggregate orderBy = new SubSonic.Aggregate(Region.Columns.RegionName, SubSonic.AggregateFunction.GroupBy);
RegionCollection regions = new RegionCollection().Where(filter).GroupBy(groupBy).Load();
The "GroupBy" part in the last line doesn't compile... (I'm using SubSonic 2.1)
Just in case there isn't a reason you need the old Where construct:
SubSonic.Aggregate groupBy = new SubSonic.Aggregate(Region.Columns.RegionName, SubSonic.AggregateFunction.GroupBy);
RegionCollection regions = new SubSonic.Select(groupBy).From(Region.Schema).Where(Region.RegionColumn).IsNotNull().ExecuteAsCollection<RegionCollection>();
With Collections you can use OrderByAsc and OrderByDesc but they both only allow passing a string as a parameter. And the SubSonic.AggregateFunction.GroupByprobably isn't what you want.
Try this instead:
var result = new RegionCollection().OrderByAsc(Region.Columns.RegionName).Load();

What is the correct way of reading single line of data by using Linq to SQL?

I'm very new to Linq, I can find multi-line data reading examples everywhere (by using foreach()), but what is the correct way of reading a single line of data? Like a classic Product Detail page.
Below is what I tried:
var q = from c in db.Products
where c.ProductId == ProductId
select new { c.ProductName, c.ProductDescription, c.ProductPrice, c.ProductDate };
string strProductName = q.First().ProductName.ToString();
string strProductDescription = q.First().ProductDescription.ToString();
string strProductPrice = q.First().ProductPrice.ToString();
string strProductDate = q.First().ProductDate.ToString();
The code looks good to me, but when I see the actual SQL expressions generated by using SQL Profiler, it makes me scared! The program executed four Sql expressions and they are exactly the same!
Because I'm reading four columns from a single line. I think I must did something wrong, so I was wondering what is the right way of doing this?
Thanks!
Using the First() extension method would throw the System.InvalidOperationException when no element in a sequence satisfies a specified condition.
If you use the FirstOrDefault() extension method, you can test against the returned object to see if it's null or not.
FirstOrDefault returns the first element of a sequence, or a default value if the sequence contains no elements; in this case the default value of a Product should be null. Attempting to access the properties on this null object will throw ArgumentNullException
var q = (from c in db.Products
where c.ProductId == ProductId
select new { c.ProductName, c.ProductDescription, c.ProductPrice, c.ProductDate }).FirstOrDefault();
if (q != null)
{
string strProductName = q.ProductName;
string strProductDescription = q.ProductDescription;
string strProductPrice = q.ProductPrice;
string strProductDate = q.ProductDate;
}
Also, you shouldn't have to cast each Property ToString() if you're object model is setup correctly. ProductName, ProductDescription, etc.. should already be a string.
The reason you're getting 4 separate sql queries, is because each time you call q.First().<PropertyHere> linq is generating a new Query.
var q = (from c in db.Products
where c.ProductId == ProductId
select new { c.ProductName, c.ProductDescription, c.ProductPrice, c.ProductDate }
).First ();
string strProductName = q.ProductName.ToString();
string strProductDescription = q.ProductDescription.ToString();
string strProductPrice = q.ProductPrice.ToString();
string strProductDate = q.ProductDate.ToString();

Resources