Dynamic load whereparameters for linqDatasource

When using an Linq Datasource (linq to sql) for a datagrid (Gridview, ListView, etc) you don't always want all rows from a table. To exclute data you can use the WhereParameters to add an where statement to your DataSource.

You can do limited where statements with the Visual Studio Wizards. When you need more than a limited statement you can dynamicly create an Parameter to add to your Linq DataSource.

The following examples shows how to filter the Linq Datasource that recovers all rows from the Post table and filters them on the BlogId. The BlogManager.CurrentBlogId gets the blog GUID from the Session.

[code:c#]

   Parameter whereparam = new Parameter();
   whereparam.Name = "BlogId";
   whereparam.DefaultValue = BlogManager.CurrentBlogId.ToString();
   whereparam.Type = TypeCode.Object;
   linqDataSource.WhereParameters.Add(whereparam);
   linqDataSource.Where = "BlogId == Guid(@BlogId)";

[/code]


You cast the @BlogId (string) to a Guid In the linqDataSource.Where property otherwise you get the following error:

Operator '==' incompatible with operand types 'Guid' and 'String'

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Web.Query.Dynamic.ParseException: Operator '==' incompatible with operand types 'Guid' and 'String'

One Reply to “Dynamic load whereparameters for linqDatasource”

  1. thanks you so much, I searched two hours for this and doesn’t known what are Guid(@param), you explain that it’s a cast and I can use it to my problem ( datetime(@myvar) )
    thank you so much! greetings from Argentina.

Leave a Reply

Your email address will not be published.