3

Many tables in my database have common fields which I call 'audit' fields. They fields like - UserUpdateId, UserCreateId, DateUpdated, DateCreated, DateDeleted, RowGUID, as well as a common "Comments" table etc. In the database they are used to track who did what when. Additionally via the asp.net MVC 4 views they display these attributes to the user using common display templates (popup, mouseover etc.).

Currently, I put these properties into a [Serializable()] CommonAttributesBase class. Which I then initialize in all the models that should inherit those properties. Admittedly this is a little clunky and inefficient as my CommonAttribute class makes calls to the repository and the initialization seems like more code than necessary.

I would appreciate suggestions on how to implement this in the best way.

[Serializable()]
public class CommonAttributesBase
{
    #region Notes
    public Boolean AllowNotes { get; set; }

    [UIHint("NoteIcon")]
    public NoteCollection NoteCollection
    {
        get
        {
            if (!AllowNotes) return null;

            INoteRepository noteRepository = new NoteRepository();
            var notes = noteRepository.FindAssociatedNotes(RowGUID);

            return new NoteCollection { ParentGuid = RowGUID, Notes = notes, AuditString = AuditTrail };
        }

    }

    #region Audit Trail related
    public void SetAuditProperties(Guid rowGuid, Guid insertUserGuid, Guid updateUserGuid, Guid? deleteUserGuid, DateTime updateDate, DateTime insertDate, DateTime? deleteDate)
    {
        RowGUID = rowGuid;
        InsertUserGUID = insertUserGuid;
        UpdateUserGUID = updateUserGuid;
        DeleteUserGUID = deleteUserGuid;
        UpdateDate = updateDate;
        InsertDate = insertDate;
        DeleteDate = deleteDate;
    }

    [UIHint("AuditTrail")]
    public string AuditTrail
    {
        get
        {
            ...code to produce readable user audit strings
            return auditTrail;
        }
    }
...additional methods
}

In another class

public partial class SomeModel
{   

    private CommonAttributesBase _common;
    public CommonAttributesBase Common
    {
        get
        {
            if (_common == null)
            {
                _common = new CommonAttributesBase { AllowNotes = true, AllowAttachments = true, RowGUID = RowGUID };
                _common.SetAuditProperties(RowGUID, InsertUserGUID, UpdateUserGUID, DeleteUserGUID, UpdateDate, InsertDate, DeleteDate);
            }
            return _common;
        }
        set
        {
            _common = value;
        }
    }

...rest of model
}

3 Answers 3

2

For me, I prefer to use different interfaces for each type (audit or note), and use decorator to retrieve those related data, instead of embedding those in the common class:

public class Note
{
    //Node properties
}

public class AuditTrail
{
    //Audit trail properties
}

public interface IAuditable
{
    AuditTrail AuditTrail { get; set; }
}

public interface IHaveNotes
{
    IList<Note> Notes { get; set; }
}

public class SomeModel : IAuditable, IHaveNotes
{
    public IList<Note> Notes { get; set; }
    public AuditTrail AuditTrail { get; set; }

    public SomeModel()
    {
        Notes = new List<Note>();
    }
}

public class AuditRepository : IRepository<T> where T : IAuditable
{
    private IRepository<T> _decorated;
    public AuditRepository(IRepository<T> decorated)
    {
        _decorated = decorated;
    }

    public T Find(int id)
    {
        var model = _decorated.Find(id);
        model.Audit = //Access database to get audit

        return model;
    }

    //Other methods
}

public class NoteRepository : IRepository<T>  where T : IHaveNotes
{   
    private IRepository<T> _decorated;
    public NoteRepository(IRepository<T> decorated)
    {
        _decorated = decorated;
    }

    public T Find(int id)
    {
        var model = _decorated.Find(id);
        model.Notes = //Access database to get notes

        return model;
    }

    //Other methods
}

Advantages is that the client will be able to choose to load audit/note or not, the logic of audit and note are also separated from the main entity repository.

1
  • I can see some of advantages here as well. The division of the interfaces allows the implementation of only the functionality required for the parent class (ex. I don't always need notes). Thanks for the response
    – John
    Feb 13, 2015 at 14:19
2

What you're doing is basically composition. As others have stated, there's many ways to accomplish what you're looking for, some better than others, but each method depends on the needs of your application, of which only you can speak to.

Composition

Composition involves objects having other objects. For example, if you were going to model a car, you might have something like:

public class Car
{
    public Engine Engine { get; set; }
}

public class Engine
{
    public int Horsepower { get; set; }
}

The benefit to this approach is that your Car ends up with a Horsepower property via Engine, but there's no inheritance chain. In other words, your Car class is free to inherit from another class while not effecting this property or similar properties. The problems with this approach is that you have to involve a separate object, which in normally is not too troubling, but when combined when tied back to a database, you're now talking about having a foreign key to another table, which you'll have to join in order to get all the class' properties.

Entity Framework allows you to somewhat mitigate this effect by using what it calls "complex types".

[ComplexType]
public class Engine
{
    ...
}

The properties of complex types are mapped onto the table for the main class, so no joins are involved. However, because of this, complex types have certain limitations. Namely, they cannot contain navigation properties -- only scalar properties. Also, you need to take care to instantiate the complex type or you can run into problems. For example, any nulled navigation property is not validated by the modelbinder, but if you have a property on your complex type that is required (which results in a property on your main class' table that is non-nullable), and you save your main class while the complex type property is null, you'll get an insertion error from the database. To be safe you should always do something like:

public class Car
{
    public Car()
    {
        Engine = new Engine();
    }
}

Or,

public class Car
{
    private Engine engine;
    public Engine Engine
    {
        get
        {
            if (engine == null)
            {
                engine = new Engine();
            }
            return engine;
        }
        set { engine = value; }
    }
}

Inheritance

Inheritance involves deriving your class from a base class and thereby getting all the members of that base class. It's the most straight-forward approach, but also the most limiting. This is mostly because all of the .NET family of languages only allow single inheritance. For example:

public class Flyer
{
    public int WingSpan { get; set; }
}

public class Walker
{
    public int NumberOfLegs { get; set; }
}

public class Swimmer
{
    public bool HasFlippers { get; set; }
}

public class Duck : ????
{
    ...
}

That's a bit contrived, but the point is that Duck is all of a Flyer, Walker and Swimmer, but it can only inherit from one of these. You have to be careful when using inheritance in languages that only allow single inheritance to make sure that what you inherit from is the most complete base class possible, because you won't be able to easily diverge from this.

Interfaces

Using interfaces is somewhat similar to inheritance, but with the added benefit that you can implement multiple interfaces. However, the downside is that the actual implementation is not inherited. In the previous example with the duck, you could do:

public class Duck : IFlyer, IWalker, ISwimmer

However, you would be responsible for implementing all the members of those interfaces on your Duck class manually, whereas with inheritance they just come through the base class.

A neat trick with interfaces and .NET's ability to extend things is that you can do interface extensions. These won't help you with things like properties, but you can move off the implementation of some of the class' methods. For example:

public static class IFlyerExtensions
{
    public static string Fly(this IFlyer flyer)
    {
        return "I'm flying";
    }
}

Then,

var duck = new Duck();
Console.WriteLine(duck.Fly());

Just by implementing IFlyer, Duck gets a Fly method, because IFlyer was extended with that method. Again, this doesn't solve every problem, but it does allow interfaces to be somewhat more flexible.

1
  • I appreciate the background an overview, it provides excellent context for the other responses. Thanks
    – John
    Feb 13, 2015 at 14:20
1

There's a couple different ways you could do something like this. I personally haven't worked with EF so I can't speak in regards to how it will work.

Option One: Interfaces

public interface IAuditable
{
  Guid RowGUID { get; }
  Guid InsertUserGUID { get; }
  Guid  UpdateUserGUID { get; }
  Guid DeleteUserGUID { get; }
  DateTime UpdateDate { get; }
  DateTime InsertDate { get; }
  DateTime DeleteDate { get; }
}

Of course you can change it to get and set if your use cases need that.

Option Two: Super/base classes

public abstract class AuditableBase 
{
     // Feel free to modify the access modifiers of the get/set and even the properties themselves to fit your use case.
     public Guid RowGUID { get; set;}
     public Guid InsertUserGUID { get; set;}
     public Guid UpdateUserGUID { get; set;}
     public Guid DeleteUserGUID { get; set;}
     public DateTime UpdateDate { get; set;}
     public DateTime InsertDate { get; set;}
     public DateTime DeleteDate { get; set;}

     // Don't forget a protected constructor if you need it!
}

public class SomeModel : AuditableBase { } // This has all of the properties and methods of the AuditableBase class.

The problem with this is that if you cannot inherit multiple base classes, but you can implement multiple interfaces.

3
  • @AZ. I suppose that's my preferred access modifier when dealing with base classes, and mostly habit also. You can change them to any that you see fit. I have altered my post to change this.
    – Cameron
    Feb 12, 2015 at 14:23
  • my question was mostly about the role of the class. It's just a data holder now and it should be used as a model presumably for data bindings. In that scenario trying to do access control on data usually is a bad idea Feb 12, 2015 at 14:53
  • Thanks so much for your response, I think i am safe with the base class approach as i won't need to inherit multiple base classes. Thanks again
    – John
    Feb 13, 2015 at 14:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.