Search code examples
c#.net-coreentity-framework-core

Check whether a generic DbSet has an Identity Key


Question: having a generic DbSet<T>, how can I know if the class T has an identity key?

This is my case:

public static string SqlCodeGenerator<T>(DbContext context) where T : class
{
    var query = string.Emtpy;
    var set = context.Set<T>();

    if (set.HasIdentity())
        query += "SET IDENTITY_INSERT ON;\n";

    // Continue building query...
}

I don't need to know which property, only if it has or has not (although gives extra points to the answer).


Solution

  • More flexible approach, not directly linked to SQL Server, but it covers Identity columns. At least those properties which are marked with [DatabaseGenerated(DatabaseGeneratedOption.Identity)] attribute

    foreach (var key in dbContext.Model.FindEntityType(typeof(Entity)).GetKeys())
    {
        foreach (var property in key.Properties)
        {
            if (property.ValueGenerated == Microsoft.EntityFrameworkCore.Metadata.ValueGenerated.OnAdd)
            {
                Console.WriteLine("gotcha!");
            }
        }
    }