'How to check using entity framework if a primary key is set to autoincrement?
I'm seeking for a way to check if my primary key is set to auto increment or not.
any help/advice is appreciated thanks!
Edit:
I have generic Forms such as (My Crud design is incomplete at the moment)
the toolstrip on the MyTestForm2 will change where there will be 3 buttons, add, edit and watch
the reason I asked this question is: on the example I provide the field CB_REFNO is primary key + it's auto incremented. when on Add/Edit I want that text box's enabled property to be set to false, but if it is not auto incremented the user needs to set it or be able to edit it. this is why I asked this question
Solution 1:[1]
I've come up with a solution, not an absolute one though. will not work if your primary key is int type and is not auto increment, so as long as you have int type primary key only in A
public static bool MyIsAutoIncrement<TEntity>(this DbContext pContext) where TEntity : class
{
var objectContext = ((IObjectContextAdapter)pContext).ObjectContext;
var set = objectContext.CreateObjectSet<TEntity>();
var myPkTypeKind = (PrimitiveTypeKind)set.EntitySet.ElementType.KeyMembers[0].GetPropValue("PrimitiveType").GetPropValue("PrimitiveTypeKind");
switch (myPkTypeKind)
{
case PrimitiveTypeKind.Int16:
return true;
case PrimitiveTypeKind.Int32:
return true;
case PrimitiveTypeKind.Int64:
return true;
}
return false;
}
Solution 2:[2]
You can also tweak in a SQL call e.g. via Dapper Retrieving Primary Key, Identity column, and specific name column from Database tables and then fiddle this back to the specific services in use.
or in ef core 6:
bool identity = context.Model.FindEntityType(ACME.GetType()).FindPrimaryKey().Properties.Any(x => x.ValueGenerated == ValueGenerated.OnAdd);
or extension method that works with synonyms also
/// <summary>
/// Call this before/after sql statement that optionally requires identity on or off
/// Calling this after could be removed by looping all idenity tables and calling OFF against all of them...
/// </summary>
public static async Task IdentityCheckAsync(this DbContext context, Type type, bool wantIdentity, bool on=true)
{
if (!wantIdentity)
{
IEntityType entityType = context.Model.FindEntityType(type);
string synonymTableName = await context.Database.GetDbConnection()
.QueryFirstOrDefaultAsync<string>($"SELECT base_object_name FROM sys.synonyms where name = @TableName", new { TableName = entityType.GetDefaultTableName() });
string tableNameFull = entityType.GetSchemaQualifiedTableName();
bool identity;
if (!string.IsNullOrWhiteSpace(synonymTableName))
{
string[] synonymTableSplitted = synonymTableName.Split('.');
identity = await context.IsIdentity(entityType, synonymTableSplitted[0], synonymTableSplitted[1], synonymTableSplitted[2]);
tableNameFull = synonymTableName;
}
else
{
identity = await context.IsIdentity(entityType);
}
if (identity)
{
string onOrOff = on ? "ON" : "OFf";
await context.Database.ExecuteSqlRawAsync($"SET IDENTITY_INSERT {tableNameFull} {onOrOff}");
}
}
}
/// <summary>
/// Checks if identity is on on a table
/// </summary>
public static async Task<bool> IsIdentity(this DbContext context, IEntityType entityType, string dbName = ""
,string dbSchema = "", string dbTable="", bool viaDb = true)
{
if (viaDb) {
string tableName = entityType.GetDefaultTableName();
string query = string.Empty;
// synonyms:
if (!string.IsNullOrWhiteSpace(dbName))
{
tableName = $"{dbTable}".Replace("[", string.Empty).Replace("]", string.Empty);
query =
$"SELECT B.name FROM {dbName}.[SYS].[IDENTITY_COLUMNS] A JOIN {dbName}.[SYS].[TABLES] B on A.object_id = B.object_id WHERE B.name = @TableName";
}
else
{
query = $"SELECT OBJECT_NAME(OBJECT_ID) AS TABLENAME FROM [SYS].[IDENTITY_COLUMNS] WHERE OBJECT_NAME(OBJECT_ID) = @TableName ";
}
string ret = await context.Database.GetDbConnection().QueryFirstOrDefaultAsync<string>(query, new { TableName = tableName });
return (!string.IsNullOrWhiteSpace(ret)); }
else {
return entityType.FindPrimaryKey().Properties.Any(x => x.ValueGenerated == ValueGenerated.OnAdd);
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | As?m Gündüz |
| Solution 2 |

