简体   繁体   中英

Convert string into lambda expression c# (linq to entity)

I'm trying to create a dynamic system which does the following:

dbContext.Users.Where(x=>(x.Initials + " " + x.Surname).Contains("someGivenString")).ToList();

In my dynamic system I have a String:

string combined = "x.Inititals + \" \" + x.Surname";

I would like to know how to use Expression.Call to create a correct query for this.

I hope my question is clear enough. Thanks in advance!

You can use runtime C# compilation . For more information and examples look here: http://www.codeproject.com/Tips/715891/Compiling-Csharp-Code-at-Runtime

To be clearly: You can for example prepare template and fulfill it with your own lambda expression, and next that string compile and run in runtime.

To expand on my comment. If your object only contain simple property convert it to datatable with something like this :

public static DataTable ObjectToData(object o)
     {
         DataTable dt = new DataTable("OutputData");

         DataRow dr = dt.NewRow();
         dt.Rows.Add(dr);

         o.GetType().GetProperties().ToList().ForEach(f =>
         {
             try
             {
                 f.GetValue(o, null);
                 dt.Columns.Add(f.Name, f.PropertyType);
                 dt.Rows[0][f.Name] = f.GetValue(o, null);
             }
             catch { }
         });

         return dt;
     }

I wrote this for my specific need but you should get the idea.

and then to do the whole select that is easy to build where clause very very custom. like

WHERE initial + ' ' + surname like '%someGivenString%'

then you simply sort or select the table for your query. i like to use that simply homemade class :

public static class CTableManager
{
    public static DataTable Select(DataTable dt, string sFilter)
    {
        DataTable dtResult = dt.Clone();

        try
        {
            dtResult = dt.Select(sFilter).CopyToDataTable();
        }
        catch { }

        return dtResult;
    }

    public static DataTable Sort(DataTable dt, string sOrder)
    {
         DataTable dtResult = dt.Clone();

         try
         {
             dt.DefaultView.Sort = sOrder;

             dtResult = dt.DefaultView.ToTable().Copy();
         }
         catch { }

         return dtResult;
    }

     public static DataTable SelectAndSort(DataTable dt, string sFilter, string sOrder)
    {
        DataTable dtResult = dt.Copy();

        if (sFilter != string.Empty)
        {
            dtResult = Select(dtResult, sFilter);
        }

        if (sOrder != string.Empty)
        {
            dtResult = Sort(dtResult, sOrder);
        }

        return dtResult;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM