How can i get rid of hard coding in creating a new EntityKey in Entity Framework
views:
196answers:
1
+1
A:
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 pluralizaed your entity-sets in .NET 3.5 (which Pluralization Service doesn't exist), 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);
}
The Pluralizer helper is from: Simple English Noun Pluralizer in C#
Shimmy
2009-06-17 15:34:29