I ran up against a unique issue this week. I have an EntityDataSource control bound to a DataView control. I also have a search form with about 10 fields the user can populate to search for data, which is then shown in the DataView.
the problem I had was that I needed the Where statement on the EntityDataSource to be set programmatically. The reason is because when you use multiple controls to populate the Where statement, the EntityDataSource control automatically uses “OR” between the various search fields. So you get a eSQL statement like this:
WHERE name = 'jim' OR phone = '5551212'
So what if you need to do an AND? Or worse, what if you need to do some logic where you use OR or AND depending on how some other field is set? Well, then you have to set the Where statement in your code behind. The problem is, the only place I found it would work is if I set it in the EntityDataSource.Load event.
OK, so why is that a problem? Well, if you set it in the Load event, the control gets refreshed on every single page refresh. Normally, ViewState is used, but you are now overwriting that with every page load. This presents a huge problem when doing Deletes.
When doing a Delete, the EntityDataSource will normally dip into the ViewState, retrieve the previously retrieved Entity, then delete it. However, since we’re doing a new query on every page load, that ViewState is trashed. So when you delete, you now have a new set of data, and the EntityDataSource doesn’t know which record to delete and will throw an error.
So what do do? Well, I discovered after MUCH playing around that the easiest way to delete my record was to simply catch the RowCommand event on the DataGrid. Do that by making your delete button a template, bind your record id to the CommandArgument of the control, then catch the RowCommand event of the grid.
Then in the RowCommand event in hyour code behind, you can use the id stored in the CommandArguments to grab the correct record from the Entity Framework, and delete it.
There’s one more thing you need to do though. You’ll need to set EnableDelet on your EntityDataSource to FALSE. Then, catch the RowDeleting event of the GridView and set the GridViewDeleteEventArgs.Cancel parameter to TRUE. That will keep your EntityDataSource from trying to delete the record you just deleted.
Yes, that seems like quite a round about way to get what I needed, but I didn’t see any other way around it. This is one of the problems with these canned data controls. They are very powerful, but all have limitations.
Hope this helps.