本机不支持索引,但如果您前往this 文章的“影响 DDL 生成”部分,您可以了解如何将此自定义功能添加到现有模板。
在本文的示例中,EDMX 的 CSDL 中的新索引如下所示:
<Property ... >
<myExtensions:Index indexName="Seat" edmx:CopyToSSDL="true"/>
</Property>
但要使其正常工作,您必须修改一些内容(有关详细信息,请参阅我提供的链接)。首先,您必须在模式节点上声明“myExtensions”命名空间:
<!-- CSDL content -->
<edmx:ConceptualModels>
<Schema [...] xmlns:myExtensions="http://www.microsoft.com/userExtensions">
[...]
</edmx>
其次,您必须修改在以下位置找到的模板:
\Microsoft Visual Studio 10.0\Common7\IDE\Extensions\Microsoft\Entity Framework Tools\DBGen\SSDLToSQL10.tt
该解决方案需要 Linq,因此将其添加到模板顶部:
<#@ assembly name="System.Xml.Linq" #>
然后将这个添加到底部:
-- Creating index for table based on custom extensions --
<#
foreach (EntitySet entitySet in Store.GetAllEntitySets())
{
string tableName = Id(entitySet.GetTableName());
string schemaName = Id(entitySet.GetSchemaName());
EdmProperties props = entitySet.ElementType.Properties;
foreach (EdmProperty ep in props.Where(p =>
p.TypeUsage.EdmType is PrimitiveType))
{
MetadataProperty meta = ep.MetadataProperties.FirstOrDefault(mp => mp.Name == "http://www.microsoft.com/userExtensions:Index");
if (meta != null)
{
System.Xml.Linq.XElement e = meta.Value as System.Xml.Linq.XElement;
System.Xml.Linq.XAttribute attr = e.Attributes().FirstOrDefault(a => a.Name == "indexName");
string indexName = attr.Value;
// create an index for specified column
#>
CREATE INDEX [IX_<#=indexName#>]
ON <#if (!IsSQLCE) {#>[<#=schemaName#>].<#}#>[<#=tableName#>]
([<#=indexName#>]);
<#
}
}
}
#>
其中大部分都可以很容易地修改以满足您的需求。本文详细介绍了更多细节,但上述代码中最重要的一行是获取自定义“索引”扩展节点的那一行:
MetadataProperty meta = ep.MetadataProperties.FirstOrDefault(mp => mp.Name == "http://www.microsoft.com/userExtensions:Index");
希望有帮助!