6

We are using EntityFramework and have already gone through a long journey with Database First. We have multiple contexts and many, many entities. While we entertain the notion of undergoing a project of code first, we want to explore the alternate possibilities available with EF.

We are using the latest version of EF as of current, 6.0.2

We have quite a few tables with common fields such as Auditing fields "CreatedBy", "CreatedDate", "UpdatedBy" and "UpdatedDate" and we thought that it would be perfect to use a ComplexType here.

In a table that uses those fields, when we generate the code from the database, it pulls the fields in raw. We then delete it in the model browser, add the complex type and then maps the complex properties to the field names in the DB.

In this experiment, we ran the "Generate database from model" without mapping the fields to see what were the resulting column names and if any convention or auto-magic would allow that behavior bi-directionally(Turning complex type into columns and recognizing columns as complex types).

This resulted in column names with the complex type suffixed with an '_' and the field name. We tested and it didn't pull the complex type back from the database in the model when we regenerated the model.

Is there a proper way to have EF detect Complex types in tables with database first? Is there some code factory, builder, strategy or template that I can write?

Our main motivation is that we have quite a number of tables to support, we embrace frequent changes and we want to prevent people on our team neglecting this step and breaking the code base.

Much appreciation for your time StackOverflowians!

-- Edit --

While this doesn't solve the problem using the auto-detection of complex types, this has resolve the issues of Developer's breaking the model each time they run the T4 template updates.

http://www.ninjacrab.com/2015/02/07/update-entityframework-detecting-complex-type-with-database-first/

3
  • Are you suggesting using Complex types to ease the use of auditing? And as a side note, I'm curious about your auditing column names. Is CreatedBy a varchar? If not, and it's actually and Id pointer then I'd suggest CreatedById. I like the readability of CreatedBy, but CreatedDate sounds a little old school, and you might consider CreatedOn (I'm not a fan of Hungarian notation). Feb 8, 2015 at 5:16
  • Yes, we use complex types to ease auditing. Totally open to other practices/ideas. Our "By" fields are varchar and not FK/pointer Ids because in our use case, we actually allow hard deletes on the reference data. Each time we write to our main table, it actually writes a record to a secondary "Auditing" table. While the actual table could(and probably should) actually have an FK to the main user, the auditing table doesn't force the reference so that we can just maintain a trail. Finally, I agree with the "On", just haven't heard that suggestion before and no one has really complained :)
    – Min
    Feb 8, 2015 at 5:50
  • Er "Used". No longer now of course as described by the post
    – Min
    Feb 8, 2015 at 5:58

1 Answer 1

1

What I did was a Generic semi-Repository pattern over EF. I also used intefaces to allow identification and automatic use of methods if they match.

Auditable Interface:

public interface IDbAuditable : IDbEntity
{
    Guid CreatedById { get; set; }
    DateTime CreatedOn { get; set; }
    Guid ModifiedById { get; set; } 
    DateTime ModifiedOn { get; set; }
    Guid? DeletedById { get; set; } 
    DateTime? DeletedOn { get; set; } 
}

(I personally like the idea that if CreatedOn == ModifiedOn then it's never been modified, some people like DateTime?, doesn't really matter they serve the same purpose.)

Since this example is in a small project, I simply wrapped the EF Context and didn't use any IoC/DI. This is a small subset of all the actual code (some methods are missing and some interfaces are missing, but it should make perfect sense).

public sealed class MyDb : IDisposable
{
    private MyContext _context;

    public MyDb(string connectionString, Lazy<Guid?> currentUserIdFunc)
    {
        this._context = new MyContext(connectionString);

        Database.SetInitializer<MyContext>(new DatabaseInitializer());
        this._context.Database.Initialize(true);

        this._currentUserIdFunc = currentUserIdFunc;
    }

    public async Task<T> GetEntityAsync<T>(Func<IQueryable<T>, IQueryable<T>> entityQuery) where T : class, IDbEntity
    {
        var query = entityQuery(this._context.Set<T>());

        if (typeof(T) is IDbAuditable)
        {
            query = query.Cast<IDbAuditable>()
                 .Where(a => !a.DeletedById.HasValue)
                 .Cast<T>();
        }

        return await query.FirstOrDefaultAsync();
    }

    public async Task<int> UpdateAsync<T>(T entity) where T : class, IDbEntity
    {
        if (entity is IDbDoNotModify)
        {
            throw new DoNotModifyException("Entity cannot be Modified (IDoNotModify).");
        }

        this._context.Set<T>().Attach(entity);
        var entry = this._context.Entry<T>(entity);
        entry.State = EntityState.Unchanged;

        var entityType = entity.GetType();

        var metadata = entityType.GetCustomAttributes(typeof(MetadataTypeAttribute)).FirstOrDefault() as MetadataTypeAttribute;
        if (metadata != null)
        {

            var type = metadata.MetadataClassType;

            var properties = type.GetProperties(BindingFlags.Instance | BindingFlags.Public)
                 .Select(p => new
                 {
                     Name = p.Name,
                     ScaffoldColumn = p.GetCustomAttributes(typeof(ScaffoldColumnAttribute), true).FirstOrDefault() as ScaffoldColumnAttribute,
                     Readonly = entityType.GetProperty(p.Name).GetCustomAttributes(typeof(ReadOnlyAttribute), true).FirstOrDefault() as ReadOnlyAttribute
                 })
                 .Where(p => (p.ScaffoldColumn == null || p.ScaffoldColumn.Scaffold)
                     && (p.Readonly == null || !p.Readonly.IsReadOnly))
                 .ToList();

            foreach (var property in properties)
            {
                entry.Property(property.Name).IsModified = true;
            }

        }
        else
        {
            entry.State = EntityState.Modified;
        }

        var auditable = entity as IDbAuditable;
        if (auditable != null)
        {
            this.Modified(auditable, this._currentUserIdFunc.Value);
            entry.Property("ModifiedOn").IsModified = true;
            entry.Property("ModifiedById").IsModified = true;
        }


        return await this._context.SaveChangesAsync();
    }

    private void Modified(IDbAuditable instance, Guid? currentUserId)
    {
        instance.ModifiedById = currentUserId.Value;
        instance.ModifiedOn = DateTime.Now;
    }
}

Here is how I would use it:

// returns the first car with a model of ford
var car = MyDb.EntityAsync<Car>((query) = query
  .Where(c => c.Model.Equals("ford")
);

// returns the first dog with an ownerId of id
var car = MyDb.EntityAsync<Dog>((query) => query
  .Where(d => d.OwnerId == Id)
);

UpdateAsync(car);

This example application is very small so I didn't implement any UnitOfWork but it could be easily modified for such a case. Additionally, the MyDb class could be turned into a MyDb<T> if you have multiple Contexts pretty easily. I allow heavy use of DataAnnotations.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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