I want to convert the following query (which is working correctly) from query syntax to LINQ syntax, but I can't seem to get it right:
SELECT
[t1].[ID], [t1].[ParentID], [t1].[FolderName],
[t1].[Purpose], [t1].[IsSystem],t1].IsHidden],
[t1].[ChangeSrc], [t1].[SyncGUID], [t1].[CreationDBTimeStamp]
FROM [dbo].[FileStorageFolders] AS [t0]
INNER JOIN [dbo].[FileStorageFolders] AS [t1] ON ([t0].[ID]) = [t1][ParentID]
WHERE ([t1].[Purpose] = #p0)
AND ([t1].[FolderName] = #p1)
AND ([t0].[ParentID] IS NULL)
AND ([t0].[Purpose] = #p2)
I use this LINQ syntax but the result always null value:
private static FileStorageFolder GetCapsuleContentFolder(FileStorageDataContext db)
{ IQueryable<FileStorageFolder> source = (from dbfolder in db.FileStorageFolders
join dbsubfolder in db.FileStorageFolders on
new { ParentID = dbfolder.ID } equals
new { ParentID = Convert.ToInt32(dbsubfolder.ParentID) }
where
dbfolder.ParentID == null &&
dbfolder.Purpose == 'REPORT' &&
dbsubfolder.Purpose == 'LayoutFolder' &&
dbsubfolder.FolderName == 'LayoutReport'
select new
{
dbsubfolder.ID,
ParentID = (System.Int32?)dbsubfolder.ParentID,
dbsubfolder.FolderName,
dbsubfolder.Purpose,
dbsubfolder.IsSystem,
pqrentID2 = dbfolder.ParentID,
Purpose2 = dbfolder.Purpose
}) as IQueryable<FileStorageFolder>;
return source.Single();
}
Do you have a collection of child foleders on parent? You should if your relation is mapped. In such case you can try:
var query = from dbFolder in db.FileStorageFolders
from subFolder in dbFolder.SubFolders // Here I use that mapped relations
where ...
select new { ... };
The problem with your query is that you are creating anonymous type and converting it to your type - it is not possible. Also it is not full hierarchical query (your SQL is not as well). It will select only one level of sub folders.
Related
I'm trying to write a LINQ for the below query,
Select DIS.iDataItemID, DIS.iDataItemCurrentStatusID, DI.iDataTypeID,
DI.iEmployeeID, DI.iEmployerID, DI.iLinkID, DI.iSystemID, DI.sData,
DI.sEmployerCode, DI.sRecieptID, COunt(*)
from OT_BackendUpdate_DataItem DI
INNER JOIN OT_BackendUpdate_DataItemStatus DIS ON DIS.iDataItemID =
DI.iDataItemID
INNER JOIN OT_BackendUpdate_RefDataItemStatus ON DIS.iDataItemCurrentStatusID
= OT_BackendUpdate_RefDataItemStatus.iDataItemStatusID
AND DIS.iDataItemCurrentStatusID = 1 AND
DIS.iDataItemCurrentStatusID IN (
SELECT top 1 iDataItemCurrentStatusID FROM OT_BackendUpdate_DataItemStatus
Where
OT_BackendUpdate_DataItemStatus.iDataItemID = DI.iDataItemID
order by OT_BackendUpdate_DataItemStatus.dDateEffective desc
)
GROUP BY DIS.iDataItemID, DIS.iDataItemCurrentStatusID, DI.iDataTypeID,
DI.iEmployeeID, DI.iEmployerID, DI.iLinkID, DI.iSystemID, DI.sData,
DI.sEmployerCode, DI.sRecieptID
I have written the LINQ as below, Need to know how to use Group by on this,
_result = from _dataItem in _msaDBContext.OT_BackendUpdate_DataItem
join _dataItemStatus in _msaDBContext.OT_BackendUpdate_DataItemStatus on _dataItem.iDataItemID equals _dataItemStatus.iDataItemID
join _refDataItemStatus in _msaDBContext.OT_BackendUpdate_RefDataItemStatus on _dataItemStatus.iDataItemCurrentStatusID equals _refDataItemStatus.iDataItemStatusID
where _dataItemStatus.iDataItemCurrentStatusID == _processingStatus.iDataItemStatusID && _systemIDs.Contains(_dataItem.iSystemID) && _dataItem.iDataTypeID == _dataType.iDataTypeID
&& (_msaDBContext.OT_BackendUpdate_DataItemStatus.Where(x=>x.iDataItemID == _dataItem.iDataItemID).OrderByDescending(x=>x.dDateEffective).Select(x=>x.iDataItemCurrentStatusID).Take(1)).Equals(_dataItemStatus.iDataItemCurrentStatusID)
group _refDataItemStatus by new
{
_dataItemStatus.iDataItemCurrentStatusID,
_dataItemStatus.iDataItemID,
_dataItem.iDataTypeID,
_dataItem.iEmployeeID,
_dataItem.iEmployerID,
_dataItem.iLinkID,
_dataItem.iSystemID,
_dataItem.sData,
_dataItem.sEmployerCode,
_dataItem.sRecieptID
} into g
select new
{
iDataItemID = g.Key.iDataItemID,
iDataItemCurrentStatusID = g.Key.iDataItemCurrentStatusID,
iDataTypeID = g.Key.iDataTypeID,
iLinkID = g.Key.iLinkID,
sData = g.Key.sData,
iEmployeeID = g.Key.iEmployeeID,
iEmployerID = g.Key.iEmployerID,
sEmployerCode = g.Key.sEmployerCode,
iSystemID = g.Key.iSystemID,
sReceiptID = g.Key.sRecieptID,
Count = g.Count()
};
The LINQ query is failing in the line,
(_msaDBContext.OT_BackendUpdate_DataItemStatus.Where(x=>x.iDataItemID == _dataItem.iDataItemID).OrderByDescending(x=>x.dDateEffective).Select(x=>x.iDataItemCurrentStatusID).Take(1)).Equals(_dataItemStatus.iDataItemCurrentStatusID)
Please let me know, how do i write the SQL IN sub-query condition using LINQ.
PFB the exception details from the above LINQ line where i'm trying to write a sub query,
"Unable to cast the type 'System.Byte' to type 'System.Object'. LINQ to Entities only supports casting EDM primitive or enumeration types."
Please let me know what am i missing here.
I need to use Linq to Entity Framework to query a LOCATION table to get the record of the location code with the MAX effective date, then use that result as a join in the next query.
I BELIEVE I need to do convert before the IQueryable is used, because I have that last clause in the second query where I want to exclude records where the FLOOR code is in the excludedSchools list. That excludedSchools list will have the newLocationCode in it.
So, I need to update the values in the IQueryable result before I use it. Can I do this? Here is my code:
using (var db = new TheContext())
{
IQueryable<LocationTable> locatinWithMaxEffDate =
(from lc in db.LocationTable
where lc.EFF_STATUS == "A" && lc.EFFDT <= DateTime.Now
group lc by lc.LOCATION into g
select g.OrderByDescending(x => x.EFFDT).FirstOrDefault()
);
foreach (var location in locatinWithMaxEffDate.ToList())
{
string newLocationCode;
if(codeMappingDictionary.TryGetValue(location.FLOOR, out newLocationCode))
{
// how do I update locatinWithMaxEffDate FLOOR value
// with newLocationCode so it works in the query below?
location.FLOOR = newLocationCode;
}
}
var query =
(from fim in db.PS_PPS_FIM_EE_DATA
join mloc in locatinWithMaxEffDate on fim.LOCATION equals mloc.LOCATION
where
fim.EMPL_STATUS == PsPpsFimEeData.EmployeeStatusValues.Active
&& fim.AUTO_UPDATE == PsPpsFimEeData.AutoUpdateValues.Enabled
&& includeJobCodes.Contains(fim.JOBCODE)
&& !excludedSchools.Contains(mloc.FLOOR)
select new PpsAdministratorResult
{
SchoolId = mloc.FLOOR,
Login = fim.OPRID,
EmployeeId = fim.EMPLID,
}
With the code above, the locatinWithMaxEffDate does not have the updated FLOOR values. I can see why this is, but can't seem to fix it.
So far, I have tried introducing another list to ADD() the new location record to, then casting that as an IQueryable, but I get an error about primitive vs concrete types.
I decided to make things easier on myself. Since both sets of data are very small (fewer than 1000 records each) I call take the entire set of data as an annonymous type:
using (var db = new TheContext())
{
IQueryable<LocationTable> locatinWithMaxEffDate =
(from lc in db.LocationTable
where lc.EFF_STATUS == "A" && lc.EFFDT <= DateTime.Now
group lc by lc.LOCATION into g
select g.OrderByDescending(x => x.EFFDT).FirstOrDefault()
);
var query =
(from fim in db.PS_PPS_FIM_EE_DATA
join mloc in locatinWithMaxEffDate on fim.LOCATION equals mloc.LOCATION
where
fim.EMPL_STATUS == PsPpsFimEeData.EmployeeStatusValues.Active
&& fim.AUTO_UPDATE == PsPpsFimEeData.AutoUpdateValues.Enabled
&& includeJobCodes.Contains(fim.JOBCODE)
select new PpsAdministratorResult
{
SchoolId = mloc.FLOOR,
Login = fim.OPRID,
EmployeeId = fim.EMPLID,
}
}
Then, just work with the two objects:
List<PpsAdministratorResult> administratorList = new List<PpsAdministratorResult>();
foreach (var location in query.ToList())
{
string newLocationCode;
if(schoolCodeMappings.TryGetValue(location.SchoolId, out newLocationCode)) // && newLocationCode.Contains(location.LOCATION))
{
location.SchoolId = newLocationCode;
}
if( !excludedSchools.Contains(location.SchoolId) )
{
administratorList.Add(location);
}
}
Now, I have the list I want.
I have 3 table
Tbl_City , Tbl_GroupCities , Tbl_CtrCar .
I want to convert this SQL query to LINQ or lambda expression in C#
declare #fk_group uniqueidentifier
SELECT #fk_group= FK_Group
FROM dbo.Tbl_User
WHERE UserName='meysam'
SELECT dbo.Tbl_City.ID_City, dbo.Tbl_City.Name_City,COUNT( dbo.Tbl_CtrCar.Cur_year)
FROM dbo.Tbl_City
INNER JOIN dbo.Tbl_CtrCar ON dbo.Tbl_City.ID_City = dbo.Tbl_CtrCar.FK_City
WHERE ID_City IN (SELECT FK_City
FROM dbo.Tbl_GroupCities
WHERE Active=1 AND ID_Group=#fk_group)
GROUP BY ID_City , Name_City
I try it but it's not work
var model = _TblUser.FirstOrDefault(x => x.UserName == "sampleUserName");
var q = _TblGroupCities.Where(x => x.IdGroup == model.FkGroup && x.Active == true);
var sample2 =
(from x in _TblCity
join a in _TblGroupCities on x.IdCity equals a.FkCity
where a.Active == true && a.IdGroup == model.FkGroup
select new
{
x.IdCity,
x.NameCity
}).ToList();
Please take a look here the features you have in your query are not yet implemented. GroupBy and i think also subselects will do an
SELECT * FROM TableName
And in memory it will do the group by or even for each row a new SQL query.
Better to use the RawSql method for this purpose.
But if you realy want to learn LINQ and convert your SQL take a look at LINQPad
This issue is done. I found my problem, I don't Understand use two joins and use group by in Linq
I use this linq for the solution and run
var model = _TblUser.SingleOrDefault(x => x.UserName == type.UserName);
var q = _TblGroupCities.Where(x => x.IdGroup == model.FkGroup && x.Active == true);
tblCityViewModel = new List<MohasebKhodro.ViewModels.TblCityViewModel>();
var sample2 =
(from x in _TblCity
join a in _TblGroupCities on x.IdCity equals a.FkCity
where a.Active == true && a.IdGroup == model.FkGroup
select new
{
x.IdCity,
x.NameCity
}).ToList();
foreach (var item in sample2)
{
var er = _TblCtrCar.Where(x => x.FkCity == item.IdCity).Max(x => x.CurYear);
tblCityViewModel.Add(new MohasebKhodro.ViewModels.TblCityViewModel
{
IdCity = item.IdCity,
NameCity = item.NameCity,
MaxCurrentYear = Convert.ToString(er)
});
}
I am using LINQ to SQL in my C# tutorial project but I have basic knowledge of it.
I made a SQL query like this:
SELECT ID,HeroName,HeroRarity,Initiative,Attack,Attack1
FROM CharactersName
WHERE ID IN(
SELECT HeroID
FROM Hero_Group
WHERE GroupID=1
)
(Hero_Group) is a table to deal with a many-to-many relation between (CharactersName) table and another table named (Groups) where a character can be in more than one group.
I tried to write it in LINQ like this:
void FilterGroup()
{
HDAEntities db = new HDAEntities();
var query = from obj in db.CharactersNames
where obj.ID == from obj2 in db.Hero_Group
where obj2.GroupID == comboBox1.SelectedIndex
select new
{
obj2.GroupID
}
select new
{
obj.ID,
obj.HeroName,
obj.HeroRarity,
obj.Initiative,
obj.Attack,
obj.Attack1
};
}
But of course this is gibberish.
Can someone help me, please ? (be informed that I have little knowledge of LINQ to SQL)
~TIA~
You can do it like this:
void FilterGroup()
{
HDAEntities db = new HDAEntities();
var subQuery = db.Hero_Group.Where(h => h.GroupID == comboBox1.selectedIndex)
.Select(h => h.GroupID);
var query = from obj in db.CharactersNames
where subQuery.Contains(obj.ID)
select new
{
obj.ID,
obj.HeroName,
obj.HeroRarity,
obj.Initiative,
obj.Attack,
obj.Attack1
};
var result = query.ToList(); // this is where your query and subquery are evaluated and sent to the database
db.Dispose();
db = null;
}
Note that the subQuery is not evaluated until you call ToList(). You also need to dispose the object (or try the using statement to create the HDAEntities object). Also, make sure you don't dispose the db before evaluating the query (calling ToList after Dispose will throw an exception).
var query = from obj in db.CharactersNames
where (from obj2 in db.Hero_Group
where obj2.GroupID == comboBox1.SelectedIndex
select new {obj2.GroupID}).Contains(obj.ID)
select new
{
obj.ID,
obj.HeroName,
obj.HeroRarity,
obj.Initiative,
obj.Attack,
obj.Attack1
};
var query = from obj in db.CharactersNames
where (from obj2 in db.Hero_Group
where obj2.GroupID == comboBox1.SelectedIndex
select new {obj2.GroupID}).Contains(obj.ID)
select new
{
obj.ID,
obj.HeroName,
obj.HeroRarity,
obj.Initiative,
obj.Attack,
obj.Attack1
};
I have a rather complex linq to entity query that I'm performing, in the end, I have a result set. I loop through that result set, build business objects and return that list of business objects. it's pretty quick, the problem is that 2 of the child properties are complex objects with their own child objects. for every business object in my loop, I then have to make 2 DB calls to fill its child object. Those 2 calls slow down the overall process, is there a better way to do this? noob to EF here. (EF 4,SQL Server 2008,c#)
Get a result set:
var newresult = from r in result // result is another complex query
join subedit in
(from sa in context.Security_Access
join g in context.Security_UserGroup on sa.EntityID equals g.GroupID
where (sa.PrivledgeID == xx) && g.UserID == userId
select new { user = g.UserID, linkid = sa.LinkID }).Distinct() on new { aid = r.AssetId } equals new { aid = subedit.linkid } into theSubEdit
from subEditAccess in theSubEdit.DefaultIfEmpty()
join subdownload in
(from sa in context.Security_Access
join g in context.Security_UserGroup on sa.EntityID equals g.GroupID
where (sa.PrivledgeID == xx|| sa.PrivledgeID == yy) && g.UserID == userId
select new { user = g.UserID, linkid = sa.LinkID }).Distinct() on new { aid = r.AssetId } equals new { aid = subdownload.linkid } into theSubDownload
from subDownloadAccess in theSubDownload.DefaultIfEmpty()
join subView in
(from sa in context.Security_Access
join g in context.Security_UserGroup on sa.EntityID equals g.GroupID
where (sa.PrivledgeID == xx|| sa.PrivledgeID == yy|| sa.PrivledgeID == 101) && g.UserID == userId
select new { user = g.UserID, linkid = sa.LinkID }).Distinct() on new { aid = r.AssetId } equals new { aid = subView.linkid } into theSubView
from subViewAccess in theSubView.DefaultIfEmpty()
select new { r, EditAccess = (int?)subEditAccess.user, DownloadAccess = (int?)subDownloadAccess.user, ViewAccess = (int?)subViewAccess.user };
I then loop through that result set:
foreach (var asset in newresult)
{
// and build a new business object, set its properties
BoAsset boAsset = new BoAsset();
boAsset.HasEditRights = (asset.EditAccess > 0);
boAsset.HasDownloadRights = (asset.DownloadAccess > 0);
boAsset.HasViewRights = (asset.ViewAccess > 0);
boAsset.Description = asset.r.Description;
boAsset.DetailedDescription = asset.r.DetailedDescription;
boAsset.Keywords = asset.r.Keywords;
boAsset.Notes = asset.r.Notes;
boAsset.Photographer = asset.r.Photographer;
boAsset.PhotographerEmail = asset.r.PhotographerEmail;
boAsset.Notes = asset.r.Notes;
boAsset.Author = asset.r.Author;
// these 2 properties i've commented out are
// complex objects/entities, setting them the way I am
// requires me to call 2 separate methods which make 2 DB trips
// per business object.
//boAsset.Domains = GetAssetDomains(asset.r.AssetId);
//boAsset.DomainEntries = GetAssetCustomDomains(asset.r.AssetId);
myListofObjects.Add(boAsset);
}
return myListofObjects;
Is there a better way?
Just add this .Include("Domains").Include("DomainEntries") to your Linq in in context.Security_Access That should get rows from those tables all in one go.
So your "inner" queries would look like:
from sa in context.Security_Access.Include("Domains").Include("DomainEntries")
join g in context.Security_UserGroup on sa.EntityID equals g.GroupID
where (sa.PrivledgeID == xx) && g.UserID == userId
select new { ...
Here is the documentation from MS: http://msdn.microsoft.com/en-us/library/bb738708.aspx
If you want to improve your performance use compile queries !
You can check the example here.
static readonly Func<AdventureWorksEntities, Decimal,
IQueryable<SalesOrderHeader>> s_compiledQuery2 =
CompiledQuery.Compile<AdventureWorksEntities, Decimal, IQueryable<SalesOrderHeader>>((ctx, total) =>
from order in ctx.SalesOrderHeaders.Include("Orders") where order.TotalDue >= total select order);
MSDN
AND
You can Introduce Include suppose to select all the employees along with their departments . If you have a navigational property, you won't need a join at all. You can use Include like this:
List<Employee> employeesWithDepartments = CreateObjectSet<Employee>().
Include(e => e.Department).
ToList();