I know you cannot cannot directly use the tSQL PIVOT function in Linq, but I cannot get the correct Linq syntax for what I feel is a simple transform (which I can do in straight tSQL)
I need to take this data set:
and pivot it into this:
Can someone please help me with the correct Linq syntax?
Here's how I can accomplish this in tSQL (both using PIVOT() and not)
Select piv.* from (
select custom_data_key, custom_data_value from dbo.kb_article_custom_data cd
inner join dbo.kb_article kb on cd.article_id = kb.article_id
where (custom_data_key='article_problem' or custom_data_key = 'article_cause' or custom_data_key='article_solution') and article_number='AKB26'
) d
pivot
(max(custom_data_value) for custom_data_key in([article_problem],[article_cause], [article_solution])) piv;
--WITHOUT USING PIVOT()
select
max(case when t.[custom_data_key]='article_problem' then t.[custom_data_value] end) as Article_problem,
max(case when t.[custom_data_key]='article_cause' then t.[custom_data_value] end) as Article_cause,
max(case when t.[custom_data_key]='article_solution' then t.[custom_data_value] end) as Article_solution
from(select custom_data_key, custom_data_value from dbo.kb_article_custom_data cd
inner join dbo.kb_article kb on cd.article_id = kb.article_id
where (custom_data_key='article_problem' or custom_data_key = 'article_cause' or custom_data_key='article_solution') and article_number='AKB26')t
This LINQ statement will get me the results in the first image above:
var query =
from a in custdata
join b in kbase on a.article_id equals b.article_id
where (a.custom_data_key == "article_problem" || a.custom_data_key == "article_cause" || a.custom_data_key == "article_solution") && b.article_number == id
select new { Key = a.custom_data_key, Value = a.custom_data_value };
Here's what is failing. I take the results of the Linq query above-
var q2 = from row in query
group row by "Value" into g
select new TO_Kbase
{
Problem= g.Where(c => c.Key =="article_problem" ).Select(c => c.Value).ToString(),
Cause = g.Where(c => c.Key =="article_cause").Select(c => c.Value).ToString(),
Solution = g.Where(c => c.Key =="article_solution").Select(c => c.Value).ToString()
};
foreach(var x in q2)
{
TO_Kbase kb = new TO_Kbase();
kb.Problem =x.Problem;
kb.Cause = x.Cause;
kb.Solution = x.Solution;
ta.Add(kb);
}
The output is this:
Problem: System.Data.Linq.SqlClient.Implementation.ObjectMaterializer`1+d__0`1[System.Data.SqlClient.SqlDataReader,System.String]
Cause: System.Data.Linq.SqlClient.Implementation.ObjectMaterializer`1+d__0`1[System.Data.SqlClient.SqlDataReader,System.String]
Solution: System.Data.Linq.SqlClient.Implementation.ObjectMaterializer`1+d__0`1[System.Data.SqlClient.SqlDataReader,System.String]