views:

466

answers:

2

Using Linq-to-SQL and Dynamic Data.

On a Dynamic Data edit screen, a dropdown lists the possible values for a foreign key.

I need to filter the values listed in this dropdown, preferably by adding a where clause on the linq-to-sql query.

Any ideas?

A: 

Well, I found a place to customize this, although I still have not found a way to override or extend the linq query for loading the data:

In the file \DynamicData\FieldTemplates\ForeignKey_Edit.ascx.cs (as per default location), in the Page_Load method the following call is made:

PopulateListControl(DropDownList1);

This can be replaced entirely with your own code. In my case, I first checked if the current table implements a custom interface I defined. If it does, use that to get the data to bind the dropdown, else pass control on to PopulateListControl.

Using Reflector, it seems that PopulateListControl ultimately uses MetaTable.GetQuery() to get a default list query for a table. Would have been nice to extent that instead.. but moving on to other things now!

Leon van der Walt
A: 

Hi Leon,

I think you already solved your problem, but I would like to register my solution, just in case it could help someone!

I followed the path sugested by you, editing the ForeignKey_Edit.ascx.cs. After the PopulateListControl(DropDownList1) line, I call a method RemoveResultsFromOtherUsers().

Here is the method:

    private void RemoveResultsFromOtherUsers()
    {
        using (var db = new FinWeb3.DynamicData.FinWebDBDataContext())
        {
            var data = db.GetTable(this.Column.Provider.ColumnType);
            var removableItems = new List<ListItem>();

            foreach (var item in data)
            {
                var dbItem = item as IDbEntity;

                if (dbItem.UserName != this.Context.User.Identity.Name)
                {
                    removableItems.Add(
                        DropDownList1.Items.FindByValue(dbItem.Id.ToString()));
                }
            }

            foreach (var item in removableItems)
            {
                DropDownList1.Items.Remove(item);
            }
        }
    }

IDbEntity is an interface that all my linq to sql classes implements. This interface has the properties Id and UserName. Here, my intent is to remove results that are not registered by the current authenticated user.

Thank you for your question and solution!

Tiago Deliberali Santos