How to intercept and modify SQL query in Linq to SQL

前端 未结 4 1287
礼貌的吻别
礼貌的吻别 2021-02-04 15:04

I was wondering if there is any way to intercept and modify the sql generated from linq to Sql before the query is sent off?

Basically, we have a record security layer,

4条回答
  •  面向向阳花
    2021-02-04 15:31

    first thing come to my mind is to modify the query and return the result in Non-LINQ format

    //Get linq-query as datatable-schema
            public DataTable ToDataTable(System.Data.Linq.DataContext ctx, object query)
            {
                if (query == null)
                {
                    throw new ArgumentNullException("query");
                }
    
                IDbCommand cmd = ctx.GetCommand((IQueryable)query);
                System.Data.SqlClient.SqlDataAdapter adapter = new System.Data.SqlClient.SqlDataAdapter();
                adapter.SelectCommand = (System.Data.SqlClient.SqlCommand)cmd;
                DataTable dt = new DataTable("sd");
    
                try
                {
                    cmd.Connection.Open();
                    adapter.FillSchema(dt, SchemaType.Source);
                    adapter.Fill(dt);
                }
                finally
                {
                    cmd.Connection.Close();
                }
                return dt;
            }
    

    try to add your condition to the selectCommand and see if it helps.

提交回复
热议问题