How can I get rid of hardcoding when creating a new EntityKey in Entity Framework

How can I get rid of hardcoding when creating a new EntityKey in Entity Framework

0


source to share


1 answer


GetType(Model).Name
GetType(Account).Name

      

which means:

Public Shared Function GetName(Of TEntity As Type)() As String
    Dim type = GetType(TEntity)
    If Not type.IsSubclassOf(GetType(EntityObject)) Then Throw New Exception("Item must inherit from EntityObject.")
    Return GetType(ObjectContextName).Name & "." & type.Name
End Function

      

If you added your objects in .NET 3.5 (which pluralization service doesn't exist) then use:



private static string ObjectContextName = typeof(Rlp.Data.Entities).Name;
public static string GetEntityName<TEntity>([Optional, DefaultParameterValue(false)]bool pluralize) where TEntity : Type
{
    Type type = typeof(TEntity);
    if (!type.IsSubclassOf(typeof(EntityObject))) throw new Exception("Item must inherit from EntityObject.");
    string entitySet = type.Name;
    if (pluralize) entitySet = Pluralizer.ToPlural(entitySet);
    return ObjectContextName + "." + entitySet;
}

      

Or even:

private static string ObjectContextName = typeof(Rlp.Data.Entities).Name;
private const string EntityIdSuffix = "Id";
public static EntityKey CreateEntityKey<TEntity>(string id , [Optional, DefaultParameterValue(false)]bool pluralize) where TEntity : Type
{
    Type type = typeof(TEntity);
    if (!type.IsSubclassOf(typeof(EntityObject))) throw new Exception("Item must inherit from EntityObject.");
    string entity = type.Name;
    string entitySet;
    entitySet = pluralize? Pluralizer.ToPlural(entity): entity;
    return new EntityKey(ObjectContextName + "." + entitySet, entity + EntityIdSuffix, id);  
}

      

Pluralizer Helper: Plain English Noun Pluralizer in C #

+2


source







All Articles