如何在实体框架中创建新的EntityKey时摆脱硬编码
答案 0 :(得分:2)
GetType(Model).Name
GetType(Account).Name
表示:
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
如果您在.NET 3.5(多元化服务不存在)中复制了您的实体集,请使用:
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;
}
甚至:
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助手来自:Simple English Noun Pluralizer in C#