Check whether a generic DbSet has an Identity Key

.net-core c# entity-framework-core

Question

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).

1
0
2/12/2020 8:19:07 PM

Accepted Answer

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!");
        }
    }
}
2
2/12/2020 8:44:31 PM

Popular Answer

Solved both with some creativity and Linq:

var efEntity = context.Model.FindEntityType(typeof(T));
var efProperties = efEntity.GetProperties();

var hasIdentity = efProperties.Any(p => (SqlServerValueGenerationStrategy)
    p.FindAnnotation("SqlServer:ValueGenerationStrategy").Value
    == SqlServerValueGenerationStrategy.IdentityColumn);

var identityProperty = efProperties.FirstOrDefault(p => (SqlServerValueGenerationStrategy)
    p.FindAnnotation("SqlServer:ValueGenerationStrategy").Value
    == SqlServerValueGenerationStrategy.IdentityColumn);

With libraries:

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;
using System.Linq;


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow