Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you catch a Save or Load event on a Linq-to-SQL class?

I have a Linq-to-SQL class, and I'd like to perform some pre-save validation before the record is persisted to the DB. In addition, once it has been saved, I'd like to have some post-save processing code.

Similarly, when a record is deleted, I'd like to have pre- and post- methods that will be called, no matter from where the context.SubmitChanges() call is made.

I don't see any methods in the generated code that I can override. The partial method OnValidate() may be sufficient for the pre-processing, but I want to ability to cancel the save if certain conditions are not met, and I don't see any hooks at all for post-processing.

Am I missing something? Or can you recommend another way of achieving the intended effect?

Thanks!

like image 607
Shaul Behr Avatar asked Apr 30 '09 09:04

Shaul Behr


People also ask

What LINQ provider do you use to query a memory based collection?

The LINQ to Objects provider enables you to query in-memory collections and arrays. If an object supports either the IEnumerable or IEnumerable<T> interface, the LINQ to Objects provider enables you to query it.

How do you query in LINQ?

In a LINQ query, the first step is to specify the data source. In C# as in most programming languages a variable must be declared before it can be used. In a LINQ query, the from clause comes first in order to introduce the data source ( customers ) and the range variable ( cust ).

Which statement relates to retrieving data via LINQ?

The foreach statement is also where the query results are retrieved. For example, in the previous query, the iteration variable num holds each value (one at a time) in the returned sequence.

How are LINQ queries executed?

LINQ queries are always executed when the query variable is iterated over, not when the query variable is created. This is called deferred execution. You can also force a query to execute immediately, which is useful for caching query results.


1 Answers

For inserts:

  1. Create a base class for your entities.

  2. Add some virtual methods.

  3. Override DataContext.SubmitChanges.

  4. Call DataContext.GetChangeSet() and iterate over the inserts applying the function you defined previously.

For reverting changes, look at my extension method.

like image 113
leppie Avatar answered Oct 19 '22 05:10

leppie