henkmollema / Dommel

CRUD operations with Dapper made simple.
MIT License
611 stars 99 forks source link

DatabaseGeneratedAttribute for non-key properties #190

Closed johncbc closed 4 years ago

johncbc commented 4 years ago

It seems common to have a few places where columns may be auto-generated by the database.

E.g. https://fluentmigrator.github.io/articles/db-functions.html

I noticed that the KeyPropertyInfo sets an IsGenerated() flag, which is checked on Insert - BuildInsertQuery.

I hacked together the following in Insert.cs in Dommel source, but not sure if it would be the desired approach.

    if (keyProperties.Any(p => p.IsGenerated && p.Property == typeProperty))
    {
        // Skip key properties marked as database generated
        continue;
    }

    if (typeProperty.GetSetMethod() != null)
    {
        var generatedOption = typeProperty.GetCustomAttribute<DatabaseGeneratedAttribute>()?
            .DatabaseGeneratedOption ?? DatabaseGeneratedOption.None;

        if (generatedOption == DatabaseGeneratedOption.None)
        {
            typeProperties.Add(typeProperty);
        }
    }
eddami commented 4 years ago

I noticed the same while working on this PR which adds support to generated properties in Dapper.FluentMap. In addition to @johncbc DatabaseGeneratedAttribute, my suggestion is to modify IPropertyResolver by returning our own PropertyInfo (same as IKeyPropertyResolver's KeyPropertyInfo) instead of System.Reflection.PropertyInfo, so we can mark generated properties and ignore them on insert and update.

henkmollema commented 4 years ago

Good suggestion. I'll look into it.

henkmollema commented 4 years ago

Fixed in #201

eddami commented 4 years ago

Added support of marking generated properties in FluentMap.Dommel. Check out my PR.