I work on asp.net core razor page . I face issue How to convert complicated sql query to entity framework core 7
Exactly I need to convert this SQL statement to LINQ to entity without write SQL statement on csharp meaning i need to use code first entity framework core 7
function below get values separated comma and convert it to list based on related Print server .
C#
public DataTable GetBranchesRelatedToServer(string PrintServer)
{
DataTable dt = new DataTable();
cmd.CommandText = ";with cte as (SELECT distinct PrintServer,REPLACE (Split.A.value('.', 'VARCHAR(4000)') , ' ', '' ) as BranchId FROM (SELECT BranchCode, PrintServer,CAST ('' + REPLACE(BranchCode, ',', '') + '' AS XML) AS String FROM [dbo].[tbl_branchPDFexe]) AS A CROSS APPLY String.nodes ('/M') AS Split(A)) select t.PrintServer,t.BranchId,b.vBranchDesc from cte t inner join [dbo].[tbl_Branch] b with(nolock) on t.BranchId=b.iBranchCode and PrintServer=@PrintServer";
return dt;
}models used is
C#
[Table("tbl_branchPDFexe")]
public class BranchPDFexe
{
public decimal Id { get; set; }
public string BranchCode { get; set; }
public string PrintServer { get; set; }
}
[Table("tbl_Branch")]
public class Branch
{
[Key]
public string iBranchCode { get; set; }
public string vBranchDesc { get; set; }
}what i try as below
but i get error
C#
System.InvalidOperationException: 'The LINQ expression 'b => b.BranchCode.Split( separator: char[] { , }, options: RemoveEmptyEntries) .AsQueryable() .Distinct() .ToList();C#
public list GetBranchesRelatedToServer(string PrintServer)
{
var distinctBranchCodesAndPrintServers = _adc.BranchPDFexe.SelectMany(b => b.BranchCode.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(bc => new { BranchCode = bc.Trim(), b.PrintServer })).Distinct().ToList();
// so How to make it by linq to entity
return list
}
Tahir AnsariRank #366 · 6.8K reputationPosted Aug 2, 2023, 1:58 PM EDT
pleas accept the answer, if it is helpful
public List GetBranchesRelatedToServer(string PrintServer) { var distinctBranchCodesAndPrintServers = _adc.BranchPDFexe .SelectMany(b => b.BranchCode.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries) .Select(bc => new { BranchCode = bc.Trim(), b.PrintServer })) .Distinct() .ToList(); var branchCodes = distinctBranchCodesAndPrintServers.Select(b => b.BranchCode).ToList(); // Fetch branches from the database based on the filtered branch codes var branches = _adc.Branches.Where(b => branchCodes.Contains(b.iBranchCode)).ToList(); return branches; }