ahmed salah

ahmed salah

  • 1.2k
  • 547
  • 61.5k

How to convert SQL query values separated comma to list by using entit

Aug 2 2023 5:26 PM

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 .

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 ('<M>' + REPLACE(BranchCode, ',', '</M><M>') + '</M>' 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

[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

System.InvalidOperationException: 'The LINQ expression 'b => b.BranchCode.Split( separator: char[] { , }, options: RemoveEmptyEntries) .AsQueryable() .Distinct() .ToList();
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
}

 


Answers (1)