Search code examples
asp.netlinq-to-sqldynamic-data

Set service field value in Dynamic Data


In my project many tables are linked to aspnet_Application table by ApplicationId foreign key. I don't want the users to view or edit it, so I'm looking for way to preset this sql table field value before the insert query is executed. I still have scaffolding enabled for this column (in order for DD to generate the right sql script) but I'm hiding this column/field in all my edit/list/insert pages.

Ideally I'm looking for a place to inject my code right before DynamicInsert is executed for any table in my LinqToSql class.

Thanks


Solution

  • So after some digging around I came up with an acceptable solution. I've created a partial class for my data context and added a partial Insert_ method for every table that's linked to the aspnet_Applications. In every method I set the ApplicationId field to current application id.

    It looks like this:

    public partial class MyDataContext
    {
        partial void InsertMyTable(MyTable instance)
        {
            instance.ApplicationId = HttpContext.Current.Session["ApplicationId"] as Guid?;
        this.ExecuteDynamicInsert(instance);
        }
    }
    

    Note that you can't execute other LINQ statements while in this method. In particular I had to store the application id in session rather than querying the aspnet_Applications table.

    While this is acceptable solution it isn't perfect (a lot of repetitive code) so if anyone knows better throw me a bone here :)