I am new to LINQToSQL. Is there a way to overwrite the “InsertOnSubmit” or “DeleteOnSubmit” methods of the DataContext class for a particular entity?
Like for example, I have a database table called Customers that has a boolean field “IsDeleted” which holds true if the user deletes a customer record from UI. If I will call the _myDataContext.Customers.DeleteOnSubmit(..), bydefault it will physically delete the record from the table which I don’t want. Instead, I want it to be logically deleted by setting the “IsDeleted” field to true.
One way of doing this is to Get the object and call the Update method (instead of Delete) after setting the property value. This will work as well but just out of curiosity, I want to know if the standard DataContext methods (InsertOnSubmit, DeleteOnSubmit etc) are over-writable? And if so, how?
Thanks
As far as I know, no they are not. If you don’t want to delete it… don’t call delete! However, some other options:
SubmitChangesand fix-up any changes (viaGetChangetSet) before callingbase.SubmitChanges– however, I’m dubious as to whether this is a good idea; it may need re-inserting the item, for example.Code:
Obviously if it needs to be more flexible you may want to use
GetTable()(rather than a rigidCustomersproperty).Updates re your comment; I honestly don’t think you can do it at that point; re the “10 places” thing… IMO you should be hiding the data-context behind a repository interface anyway, so all 10 places would be calling a method like
CreateUserwhich deals with the data-context and necessary logic (perhaps with a separate business logic class to handle some of the rules). And further, uniqueness should usually be handled at the database level anyway (via a constraint) due to concurrency concerns.But to do what you want before trying to save them: