I have been given a SQL query that I need to translate into LINQ, that's not a problem but there are a couple of items that I need help with in this particular query and those are the selecting column name as '' and also the concatination. Here is the query in question:
SELECT vessel_idx,
vessel_name,
spotlist_dp,
spotlist_bhp,
spotlist_deck,
spotlist_bp,
spotlist_oilrec,
spotlist_fifi,
spotlist_rov,
'' AS fixture_charterer,
'' AS fixture_work,
CONCAT( fixture_charterer ,
' ',
mid(fixture_start,9,2),
'/',
mid(fixture_start,6,2)) AS next_charterer_info,
'' AS fixture_location,
'0000-00-00 00:00:00' AS fixture_stop,
'' AS fixture_note
FROM tbl_vessels
WHERE vessel_type='AHTS'
AND current_location_spotlist_id = 2
AND fixture_start > '2016-02-12 08:30:00'
AND vessel_status = 'PPT'
ORDER BY fixture_stop
The usual stuff like AND, WHERE etc I can deal with it's purly these sections I'm struggling with. The selecting column as '':
SELECT '' AS fixture_charterer,
'' AS fixture_work,
and the concatination
CONCAT( fixture_charterer ,
' ',
mid(fixture_start,9,2),
'/',
mid(fixture_start,6,2)) AS next_charterer_info,
'' AS fixture_location,
'0000-00-00 00:00:00' AS fixture_stop,
'' AS fixture_note
Many thanks
SELECT AS is represented as:
var demo = from vessel in db.tbl_vessels
select new {
fixture_charterer = "",
fixture_work = ""
};
CONCAT is:
var demo = from vessel in db.tbl_vessels
select new {
fixture_note = fixture_charterer + " " + next_charterer_info
};
You can select constants like "" easily:
var q = from v in ....
....
select new
{
...,
fixture_charterer = "",
fixture_work = "",
next_charterer_info =
(v.fixture_charterer ?? "") + " "
+ (v.fixture_start == null ? "" : v.fixture_start.Substring(8,2))
};
Related
var providerTypes = from provider_types in dbContext.vw_LookUpProviderType
select new vw_LookUpProviderType
{
ApplicationUser = provider_types.ApplicationUser,
ProviderTypeId = provider_types.ProviderTypeId,
Type = provider_types.Type
};
var query =
from providerCoi in dbContext.Provider_COI
where providerCoi.COIProviderId == message.ProviderId
join providerDetail in dbContext.ProviderDetail
on providerCoi.ProviderId equals providerDetail.ProviderId
into providerDetails
from providerDetail in providerDetails.DefaultIfEmpty()
select new Result
{
PhysicianAdvisorId = providerCoi.ProviderId,
HasConflictOfInterest = providerCoi.COIFlag == true,
PhysicianAdvisorName = providerDetail.FirstName + " " + providerDetail.MiddleName + " " + providerDetail.LastName,
ProviderType = providerTypes
.Where(providerType => providerDetail.ProviderTypeIds.Contains(providerType.ProviderTypeId.ToString()))
.Select(providerType => providerType.Type)
.ToArray<string>()
.Aggregate((current, next) => current +", " + current)
};
I have selected the providerTypes. There is table providerDetails, and and there there is field providerTypeIds - this is can't be changed. For example providerTypes: [1: 'Type 1', 2: 'Type 2', 3: 'Type 4'] and providerTypeIds: '1,2,':
Select from providerTypes that types that can be found in providerIdsString
providerTypes.Where(providerType => providerDetail.ProviderTypeIds.Contains(providerType.ToString())) // => [1: 'Type 1', 2: 'Type 2']
Than select on string representations: .Select(providerType => providerType.Type) // => ['Type 1', 'Type 2']
And finally transform all of them into string of types separated by comma:
.ToArray<string>()
.Aggregate((current, next) => current +", " + current) // => 'Type 1, Type 2
And this is throws an exception
LINQ to Entities does not recognize the method 'System.String
Aggregate[String](System.Collections.Generic.IEnumerable1[System.String],
System.Func3[System.String,System.String,System.String])'
So, as was mentioned in comments, Aggregate function is not supported in Linq to Entities, see ref for more details: https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/ef/language-reference/supported-and-unsupported-linq-methods-linq-to-entities#aggregate-methods
Unfortunetely simple toList, didn't help me, I don't know the certain reason, but maybe it because of use field for search - providerTypes, maybe toList on the providerTypes could help, but I've used another workaround - select physicianIds string, and then manualy transform it. See code below.
//select provider types lookup, from there can map id with it text meaning, f.e.[{providerTypeId: 1, type: 'Value 1' },{providerTypeId: 2, type: 'Value 2' }]
var providerTypes = exUrDataContext.vw_LookUpProviderType.ToList();
//select physicianCois with unmodified providerTypeIds(f.e '1,2,')
var physicianCois =
await (from providerCoi in dbContext.Provider_COI
where providerCoi.COIProviderId == message.PhysicianId
join providerDetail in exUrDataContext.vw_ProviderDetail
on providerCoi.ProviderId equals providerDetail.ProviderId
into providerDetails
from providerDetail in providerDetails.DefaultIfEmpty()
select new Result
{
PhysicianAdvisorId = providerCoi.ProviderId,
HasConflictOfInterest = providerCoi.COIFlag == true,
PhysicianAdvisorName = providerDetail.FirstName + " " + providerDetail.MiddleName + " " + providerDetail.LastName,
ProviderType = providerDetail.ProviderTypeIds
}).ToListAsync();
//map string with ids to string from text values, f.e. '1,2' => 'Value 1, Value 2'
foreach (var physicianCoi in physicianCois)
{
string physicianProviderNames = "";
foreach (var providerKey in physicianCoi.ProviderType.Split(new char[] { ',' }, System.StringSplitOptions.RemoveEmptyEntries))
{
if (!physicianProviderNames.Equals(""))
{
physicianProviderNames += ", ";
}
physicianProviderNames += providerTypes.Where(providerType => providerType.ProviderTypeId == int.Parse(providerKey)).FirstOrDefault().Type;
}
physicianCoi.ProviderType = physicianProviderNames;
}
I've recently started to use Always Encrypted with SQL Server 2016 to encrypt sensitive information.
For the most part, everything has been plain sailing with regards to seamless transition.
One thing has cropped up though, the following error -
Operand type clash: nvarchar(255) encrypted with (encryption_type =
'RANDOMIZED', encryption_algorithm_name =
'AEAD_AES_256_CBC_HMAC_SHA_256', column_encryption_key_name =
'CEK_AutoK2', column_encryption_key_database_name = 'hrsys') is
incompatible with nvarchar Statement(s) could not be prepared.
The method that is throwing this exception is the following -
public ActionResult GetStaffList(string term)
{
var staffs = from e in db.Staffs
where e.FirstName.Contains(term) || e.LastName.Contains(term)
&& e.EmploymentStatus == "Active"
select new
{
label = e.FirstName + " " + e.LastName,
id = e.Id
};
return (Json(staffs, JsonRequestBehavior.AllowGet));
}
But, if I modify the method, to this-
public ActionResult GetStaffList(string term)
{
var staffSearch= db.Staffs
.ToList()
.Where(e => e.FirstName.Contains(term) || e.LastName.Contains(term))
.Where(e => e.EmploymentStatus == "Active");
var staffs = from e in staffSearch
select new
{
label = e.FirstName + " " + e.LastName,
id = e.Id
};
return (Json(staffs, JsonRequestBehavior.AllowGet));
}
It doesn't throw an error.
Is there anyway of consolidating the two 'query' variables to a single one, making sure that the data is returned as JSON with the following block -
select new
{
label = e.FirstName + " " + e.LastName,
id = e.Id
}
Also what I cant get my head around is that when querying with 'from e .....' it throws an error, but when querying with 'db.Staff ...' it doesn't.
So I most likely have something wrong, I know this already. I am just unable to figure out what exactly is wrong. I have tried this two different ways and I get different results from each way.
Well here goes, I am trying to use Stored Procedures to get data for the view. I have two View Models that are as such:
public class CharacterCraftNamesListViewModel
{
public string CharFullName { get; set; }
public string ProfName { get; set; }
}
and
public class CharacterCraftCraftListViewModel
{
public string CraftClassName { get; set; }
public int CharCraftCharID { get; set; }
public int CharCraftClassID { get; set; }
public int CharCraftLevelID { get; set; }
public bool CraftLevelSet { get; set; }
public string CraftLevelName { get; set; }
public bool CraftLevelMastery { get; set; }
}
I also have the two corresponding Stored Procedures in the database.
CREATE PROCEDURE [dbo].[GetCharacterCraftCharacterNameProfessionName]
#CharID int = NULL
AS
WITH CHCRNames_CTE ( [CCCID], [CharFull], [ProfName] )
AS
(SELECT
Character_Char_ID,
CASE
WHEN b.Char_Last_Name IS NULL THEN b.Char_First_Name
ELSE b.Char_First_Name + ' ' + b.Char_Last_Name
END AS FullName,
c.Profession_Name
FROM CharacterCraft a LEFT OUTER JOIN
[Character] b ON a.Character_Char_ID = b.Char_ID LEFT OUTER JOIN
[Profession] c ON c.Profession_ID = b.Profession_Profession_ID
)
SELECT DISTINCT CharFull, ProfName
FROM CHCRNames_CTE
WHERE CCCID = #CharID
and
CREATE PROCEDURE [dbo].[GetCharacterCraftRank]
#CharID int = NULL,
#Rank int = NULL
AS
WITH CHCR_CTE ( [Rank], [CCID], [CCCCID], [CCName], [CLCLID], [CLName], [CLTier], [CLS], [CLM])
AS
(SELECT
DENSE_RANK() OVER(PARTITION BY(a.Character_Char_ID)ORDER BY (a.CraftClass_Craft_Class_ID)) AS [Rank],
a.Character_Char_ID,
CraftClass_Craft_Class_ID,
c.Craft_Class_Name,
CraftLevel_Craft_Level_ID,
d.Craft_Level_Name,
d.Craft_Level_Tier,
Craft_Level_Set,
Craft_Level_Mastery
FROM CharacterCraft a LEFT OUTER JOIN
[Character] b ON a.Character_Char_ID = b.Char_ID LEFT OUTER JOIN
[CraftClass] c ON a.CraftClass_Craft_Class_ID = c.Craft_Class_ID LEFT OUTER JOIN
[CraftLevel] d ON a.CraftLevel_Craft_Level_ID = d.Craft_Level_ID
)
SELECT [CCID], [CCCCID], [CCName], [CLCLID], [CLS], [CLName], [CLM]
FROM CHCR_CTE
WHERE [CCID]= #CharID AND [Rank] = #Rank
ORDER BY [Rank], [CLTier]
Inside my controller I have the following:
public async Task<ActionResult> Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var names = await db.Database.SqlQuery<CharacterCraftNamesListViewModel>( sql: "GetCharacterCraftCharacterNameProfessionName", parameters: new object[] { id } ).ToListAsync();
var alist = await db.Database.SqlQuery<CharacterCraftCraftListViewModel>( sql: "GetCharacterCraftRank", parameters: new object[] { id, 1 } ).ToListAsync();
var blist = await db.Database.SqlQuery<CharacterCraftCraftListViewModel>( sql: "GetCharacterCraftRank", parameters: new object[] { id, 2 } ).ToListAsync();
var clist = await db.Database.SqlQuery<CharacterCraftCraftListViewModel>( sql: "GetCharacterCraftRank", parameters: new object[] { id, 3 } ).ToListAsync();
var characterCraft = new CharacterCraftViewModel()
{
CharNames = names.AsEnumerable(),
CraftListA = alist.AsEnumerable(),
CraftListB = blist.AsEnumerable(),
CraftListC = clist.AsEnumerable()
};
if (characterCraft == null)
{
return HttpNotFound();
}
return View(characterCraft);
}
When I look at the debugger I see the following:
id 1
names Count=0
alist Count=0
blist Count=0
clist Count=0
characterCraft
{LotroMvc.Models.CharacterCraftViewModels.CharacterCraftViewModel}
So with this I just end up getting a blank page.
Now I have tried placing the stored procedures in the controller itself, and have ended up with a different output in the debugger.
Inside the controller I tried:
public async Task<ActionResult> Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var query = "WITH CHCRNames_CTE( [CCCID], [CharFull], [ProfName] ) "
+ "AS "
+ "( SELECT "
+ "Character_Char_ID, "
+ "CASE "
+ "WHEN b.Char_Last_Name IS NULL THEN b.Char_First_Name "
+ "ELSE b.Char_First_Name + ' ' + b.Char_Last_Name "
+ "END AS FullName, "
+ "c.Profession_Name "
+ "FROM CharacterCraft a LEFT OUTER JOIN "
+ "dbo.[Character] b ON a.Character_Char_ID = b.Char_ID LEFT OUTER JOIN "
+ "dbo.[Profession] c ON c.Profession_ID = b.Profession_Profession_ID "
+ ") "
+ "SELECT DISTINCT CharFull, ProfName "
+ "FROM CHCRNames_CTE "
+ "WHERE CCCID = #p0";
var names = await db.Database.SqlQuery<CharacterCraftNamesListViewModel>( query, id ).ToListAsync();
var rank = "WITH CHCR_CTE( [Rank], [CCID], [CCCCID], [CCName], [CLCLID], [CLName], [CLTier], [CLS], [CLM] )"
+ "AS "
+ "( SELECT "
+ "DENSE_RANK() OVER(PARTITION BY(a.Character_Char_ID)ORDER BY (a.CraftClass_Craft_Class_ID)) AS [Rank], "
+ "a.Character_Char_ID, "
+ "CraftClass_Craft_Class_ID, "
+ "c.Craft_Class_Name, "
+ "CraftLevel_Craft_Level_ID, "
+ "d.Craft_Level_Name, "
+ "d.Craft_Level_Tier, "
+ "Craft_Level_Set, "
+ "Craft_Level_Mastery "
+ "FROM CharacterCraft a LEFT OUTER JOIN "
+ "[Character] b ON a.Character_Char_ID = b.Char_ID LEFT OUTER JOIN "
+ "[CraftClass] c ON a.CraftClass_Craft_Class_ID = c.Craft_Class_ID LEFT OUTER JOIN "
+ "[CraftLevel] d ON a.CraftLevel_Craft_Level_ID = d.Craft_Level_ID "
+ ") "
+ "SELECT [CCID], [CCCCID], [CCName], [CLCLID], [CLS], [CLName], [CLM] "
+ "FROM CHCR_CTE "
+ "WHERE [CCID]= #p0 AND [Rank] = #p1 "
+ "ORDER BY [Rank], [CLTier]";
var alist = await db.Database.SqlQuery<CharacterCraftCraftListViewModel>( rank, parameters: new object[] { id, 1 } ).ToListAsync();
var blist = await db.Database.SqlQuery<CharacterCraftCraftListViewModel>( rank, parameters: new object[] { id, 2 } ).ToListAsync();
var clist = await db.Database.SqlQuery<CharacterCraftCraftListViewModel>( rank, parameters: new object[] { id, 3 } ).ToListAsync();
var characterCraft = new CharacterCraftViewModel()
{
CharNames = names.AsEnumerable(),
CraftListA = alist.AsEnumerable(),
CraftListB = blist.AsEnumerable(),
CraftListC = clist.AsEnumerable()
};
if (characterCraft == null)
{
return HttpNotFound();
}
return View(characterCraft);
}
This gives me the following in the debugger:
this {LotroMvc.Controllers.CharacterCraftsController}
id 1
query "WITH CHCRNames_CTE( [CCCID], [CharFull], [ProfName] ) AS (
SELECT Character_Char_ID, CASE WHEN b.Char_Last_Name IS NULL THEN
b.Char_First_Name ELSE b.Char_First_Name + ' ' + b.Char_Last_Name
END AS FullName, c.Profession_Name FROM CharacterCraft a LEFT OUTER
JOIN dbo.[Character] b ON a.Character_Char_ID = b.Char_ID LEFT OUTER
JOIN dbo.[Profession] c ON c.Profession_ID =
b.Profession_Profession_ID ) SELECT DISTINCT CharFull, ProfName FROM
CHCRNames_CTE WHERE CCCID = #p0" names Count = 1
[0] {LotroMvc.Models.CharacterCraftViewModels.CharacterCraftNamesListViewModel}
CharFullName null
ProfName "Historian"
rank "WITH CHCR_CTE( [Rank],
[CCID], [CCCCID], [CCName], [CLCLID], [CLName], [CLTier], [CLS],
[CLM] )AS ( SELECT DENSE_RANK() OVER(PARTITION
BY(a.Character_Char_ID)ORDER BY (a.CraftClass_Craft_Class_ID)) AS
[Rank], a.Character_Char_ID, CraftClass_Craft_Class_ID,
c.Craft_Class_Name, CraftLevel_Craft_Level_ID, d.Craft_Level_Name,
d.Craft_Level_Tier, Craft_Level_Set, Craft_Level_Mastery FROM
CharacterCraft a LEFT OUTER JOIN [Character] b ON
a.Character_Char_ID = b.Char_ID LEFT OUTER JOIN [CraftClass] c ON
a.CraftClass_Craft_Class_ID = c.Craft_Class_ID LEFT OUTER JOIN
[CraftLevel] d ON a.CraftLevel_Craft_Level_ID = d.Craft_Level_ID )
SELECT [CCID], [CCCCID], [CCName], [CLCLID], [CLS], [CLName],
[CLM] FROM CHCR_CTE WHERE [CCID]= #p0 AND [Rank] = #p1 ORDER BY
[Rank], [CLTier]"
alist Count = 9
[0] {LotroMvc.Models.CharacterCraftViewModels.CharacterCraftCraftListViewModel}
CharCraftCharID 0
CharCraftClassID 0
CharCraftLevelID 0
CraftClassName null
CraftLevelMastery false
CraftLevelName null
CraftLevelSet false
(and so forth)
While the data in the alist is definitely wrong the count for it is correct. The names displays the correct ProfName but the incorrect data on the CharFullName. So I am lost with what to do here. If I execute the stored procedures in T-SQL I get the correct data displayed, but that is on the server alone. I have been unable to make MVC and SQL play correctly, and I know it is my code. I just cannot see what is wrong with the code. Any thoughts to where I went wrong?
Ok, I have figured this out. There were two things wrong that were causing the issue. With the following code, the program was not calling it to the SQL Server correctly:
var names = await db.Database.SqlQuery<CharacterCraftNamesListViewModel>( sql: "GetCharacterCraftCharacterNameProfessionName", parameters: new object[] { id } ).ToListAsync();
var alist = await db.Database.SqlQuery<CharacterCraftCraftListViewModel>( sql: "GetCharacterCraftRank", parameters: new object[] { id, 1 } ).ToListAsync();
var blist = await db.Database.SqlQuery<CharacterCraftCraftListViewModel>( sql: "GetCharacterCraftRank", parameters: new object[] { id, 2 } ).ToListAsync();
var clist = await db.Database.SqlQuery<CharacterCraftCraftListViewModel>( sql: "GetCharacterCraftRank", parameters: new object[] { id, 3 } ).ToListAsync();
While the SQLQuery call is correct through everything I have read, when I placed into SSMS what was outputted by the program, I got null sets. So I changed the sql: "GetCharacterNameProfessionName" and sql: "GetCharacterCraftRank" to sql: "GetCharacterNameProfessionName #p0" and sql: "GetCharacterCraftRank #p0, #p1". This then game me an output similar to when I wrote the queries out in the controller.
The next issue came down to naming convention. I was really baffled when I did a Database First Model to see what would happen, and it actually worked. But I realized as I was doing that I was able to map the names of my stored procedure columns to columns I had in the code. That is when it dawned on me, as simple change to my stored procedures, to have the column names match what I was putting in the program and everything worked correctly. A few minor tweaks and now my get controller looks like this:
public async Task<ActionResult> Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var characterCraft = new CharacterCraftViewModel()
{
CharNames = await db.Database.SqlQuery<CharacterCraftNamesListViewModel>(sql: "GetCharacterCraftCharacterNameProfessionName #p0", parameters: new object[] { id }).FirstAsync(),
CraftListA = await db.Database.SqlQuery<CharacterCraftCraftListViewModel>(sql: "GetCharacterCraftRank #p0, #p1", parameters: new object[] { id, 1 }).ToListAsync(),
CraftListB = await db.Database.SqlQuery<CharacterCraftCraftListViewModel>(sql: "GetCharacterCraftRank #p0, #p1", parameters: new object[] { id, 2 }).ToListAsync(),
CraftListC = await db.Database.SqlQuery<CharacterCraftCraftListViewModel>(sql: "GetCharacterCraftRank #p0, #p1", parameters: new object[] { id, 3 }).ToListAsync()
};
if (characterCraft == null)
{
return HttpNotFound();
}
return View(characterCraft);
}
I hope that this helps someone else.
What is the best approach to take to write a concat in Linq? I know that the official word is that you can't but I've heard that there are ways you can accomplish it and I need help to do this. I have a SQL Statement that reads as follows:
CONCAT(
[event_organiser] ,
' ', DATEPART(dd,[event_start]),
'/', DATEPART(mm, [event_start]))
AS organiser_info
I need to create this in Linq but I'm not sure how to based on my current setup. Here is my current select statement.
var datacontext = db.tbl_events.AsQueryable();
IQueryable<EventsViewModel> theevent = (
from v in datacontext
where v.event_start == null
select new EventsViewModel
{
event_idx = v.event_idx,
event_name = v.event_name
...concat goes here..
});
Thank you for the feedback on this question your comments and examples led me to the answer based on what you have shown me. Here is what worked for my particular scenario
next_charterer_info = string.Concat(p.fixture_charterer ?? "", " ", p.fixture_start.Value.Day, "/", p.fixture_start.Value.Month),
Thanks again
Just use "+" to join the strings?
from v in datacontext
where v.event_start == null
select new EventsViewModel
{
event_idx = v.event_idx,
event_name = v.event_name
organiser_info = event_organiser + ' ' + ...
});
You can use SqlFunctions (https://msdn.microsoft.com/en-us/library/system.data.objects.sqlclient.sqlfunctions.datepart(v=vs.110).aspx)
IQueryable<EventsViewModel> theevent = (
from v in datacontext
where v.event_start == null
select new EventsViewModel
{
event_idx = v.event_idx,
event_name = v.event_name
organiser_info = v.event_organiser + ' ' + DatePart("dd", v.event_start)
});
Other option is to include all needed columns and extend your EventsViewModel with a getter property:
public class EventsViewModel
{
...
public string organiser_info
{
get
{
return string.format("{0} {1} / {2}",
event_organiser,
event_start.ToString("dd"),
event_end.ToString("MM"))
}
}
}
Using this approach you will not be confronted with any non-translatable code constructs in Linq to Entities
var theevent = (
from v in datacontext
where v.event_start == null
select new EventsViewModel
{
event_idx = v.event_idx,
event_name = v.event_name
organiser_info = string.Format("{0} {1}/{2}", event_organiser ?? "", event_start.Date.ToString("d"), event_start.Date.ToString("M"))
});
UPDATE
String.Concat(string, string, string) is significantly faster than String.Format(). Also you can write that like this:
organiser_info = string.Concat(event_organiser ?? ""," ", event_start.Date.ToString("d"), event_start.Date.ToString("M"))
UPDATE2
Solution for retrive IQueryable odject:
IQueryable<EventsViewModel> theevent = (
from v in datacontext
where v.event_start == null
select new EventsViewModel
{
event_idx = v.event_idx,
event_name = v.event_name,
organiser_info = v.event_organiser ?? "" +
v.event_organiser ? " " : "" +
v.event_end ? SqlFunctions.DatePart("Day", v.event_end) : "" +
v.event_end ? SqlFunctions.DatePart("Month", v.event_end) : ""
}
Dont forget add using System.Data.Objects.SqlClient for SqlFunctions.DatePart.
From MSDN
This function is translated to a corresponding function in the
database. For information about the corresponding SQL Server function,
see DATEPART (Transact-SQL).
i having problem in sql by using ExecuteStoreQuery Please see the example at below
My coding
private void ChildMenuItem()
{
using (LEWREDBEntities ctx = new LEWREDBEntities())
{
string result = #"
WITH ctLevel
AS
(
SELECT
C_TASK_ID AS Child
,P_Task_ID AS Parent
,common_task. TASK_SEQ AS taskSeq
,1 AS [Level]
,CAST( TASK_SEQ AS VARCHAR(MAX)) AS [taskOrder]
,CAST (Replicate('', 1) + common_task.TASK_NAME AS VARCHAR(MAX)) AS [Task_Name]
FROM
[COMMON.TASK_REL] as common_task_rel,
[COMMON.TASK] as common_task
WHERE
common_task_rel.C_TASK_ID = common_task.TASK_ID
and common_task.[TASK_TYPE] = 'F' AND common_task.[MODULE_CODE] = 'PRODE' AND common_task.[STATUS] <> 'D'
and C_TASK_ID =357
UNION ALL
SELECT
C_TASK_ID AS Child
,P_Task_ID AS Parent
,common_task. TASK_SEQ AS taskSeq
,[Level] + 1 AS [Level]
,[taskOrder] + '.' + CAST(TASK_SEQ AS VARCHAR(MAX)) AS [taskOrder]
,CAST (Replicate('', [Level] + 1) + common_task.TASK_NAME AS VARCHAR(MAX)) AS [Task_Name]
FROM
[COMMON.TASK_REL]as common_task_rel
INNER JOIN
ctLevel
ON
( P_Task_ID = Child ) ,
[COMMON.TASK] as common_task
WHERE
common_task_rel.C_TASK_ID = common_task.TASK_ID
and common_task.[TASK_TYPE] = 'F' AND common_task.[MODULE_CODE] = 'PRODE' AND common_task.[STATUS] <> 'D'
)
SELECT
common_task.Task_Name,
common_task_url.TASK_URL,
ctLevel.CHILD
FROM
ctLevel,
[COMMON.ACL] as common_acl,
[COMMON.STAFF_ROLE] as common_staff_role,
[COMMON.TASK_URL] as common_task_url,
[COMMON.TASK] as common_task,
[COMMON.STAFF_MODULE] as common_staff_module,
[common.module] as common_module
where ctLevel.Level =3
and ctLevel.Child = common_acl.TASK_ID
and common_acl.READ_ACCESS ='Y'
and common_acl.STATUS <>'D'
and common_acl.ROLE_ID = common_staff_role.ROLE_ID
and common_staff_role.STATUS <>'D'
and common_staff_role.STAFF_ID ='user'
and common_staff_role.STAFF_ID = common_staff_module.STAFF_ID
and common_staff_module.MODULE_CODE =common_module.MODULE_CODE
and common_staff_module.STATUS<>'D'
and common_staff_module.MODULE_CODE = common_module.MODULE_CODE
and common_module.STATUS <>'D' and common_module.MODULE_CODE ='PRODE'
and common_acl.TASK_ID = common_task.TASK_ID
and common_task.STATUS <>'D'
and common_task.TASK_TYPE ='F'
and common_task.TASK_POSITION ='S'
and common_task.TASK_ID = common_task_url.TASK_ID
and common_task_url.DEFAULT_URL ='Y'
and common_task_url.STATUS<>'D'
Group By
[taskOrder],common_task.Task_Name, TASK_URL,ctLevel.CHILD
order by [taskOrder],common_task.Task_Name, TASK_URL,ctLevel.CHILD";
var query = ctx.ExecuteStoreQuery<dlcGvTask>
(result);
foreach (dlcGvTask gvTask in query.ToList())
{
MenuItem navigation = new MenuItem(gvTask.TASK_NAME, gvTask.Child.ToString(), "","");
MenuChild.Items.Add(navigation);
}
//Here????
var id = (from table in query
select table.Child).Take(1);
;
}
}
Now i got a question.How can i select the top 1 of the Record?
In your code
//Here????
var id = (from table in query
select table.Child).Take(1);
Try
var id = query.First();
//Or
var id = query.Take(1);
Try to do something like this:-
Select Top 1 ..... ;
OR
..... Where ROW_NUMBER() = 1;