Update method is not virtual #652
-
Hi everyone, I have to create an audit table for all updated records in the database but I was forbidden to use sql procedure like triggers/controls/events... So, I decided to inherit the Database class of Petapoco and override the Update method in order to store my audit record like everytime an Update() is call in my code. Every record in audit should track the object changed in json format, the type of the object changed, the user and the date. The problem here is that Upload method is private and so, it is not overridable... Do you have some suggestions for me to solve this issue using only the back-end code and without using sql code? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
First, a slight correction: However, you can create your own descendant class and re-implement the Here's an example of what I mean. public class MyDatabase: Database
{
// Need to implement some constructors and call the base constructor
public new int Update(object poco)
{
// Do your audit logging here, then:
return base.Update(poco);
}
} A second approach would be to create your own class that wraps public class MyDatabaseWrapper
{
private readonly Database _database;
public MyDatabaseWrapper()
{
// instantiate _database
}
public int Update(object poco)
{
// do your audit logging, then:
return _database.Update(poco);
}
} A third option, possibly the simplest, would be to define some extension methods to do what you want. public static class DatabaseExtensions
{
public static int AuditAndUpdate(this Database db, object poco)
{
// Do audit logging, then:
return db.Update(poco);
}
}
var db = new Database(...);
db.AuditAndUpdate(somePoco); |
Beta Was this translation helpful? Give feedback.
First, a slight correction:
Database.Update()
is public, not private, but you're right that it's not virtual and therefore can't be overridden.However, you can create your own descendant class and re-implement the
Update()
methods with thenew
keyword. Many of theUpdate()
overloads just call other overloads; it looks like there are 4 you'd have to re-implement. You'd also have to make sure that whenever you're passing around a database variable, the variable is of your own type rather thanDatabase
orIDatabase
-- otherwise your methods won't get called.Here's an example of what I mean.