下面是域名:
public class Citation
{
public Guid Id { get; set; }
public string CitationNumber { get; set; }
public DateTime CitationDate { get; set; }
public decimal Amount { get; set; }
}和Fluent API:
ToTable("Citations");
HasKey(c => c.Id);
Property(c => c.Id)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
Property(c => c.CitationNumber)
.HasMaxLength(8)
.IsRequired();
Property(c => c.CitationDate)
.IsRequired();
Property(c => c.CitationAmount)
.HasColumnType("Money")
.IsRequired();默认情况下,将在Guid字段Id上添加索引。为了提高性能,我想将索引移到CitationNumber,这也是一个唯一的值字段。
因此,SQL脚本应该如下所示:
ALTER TABLE dbo.Citations
DROP CONSTRAINT [PK_dbo.Citations]
GO
ALTER TABLE dbo.Citations ADD CONSTRAINT
[PK_dbo.Citations] PRIMARY KEY NONCLUSTERED (Id)
ALTER TABLE dbo.Citations ADD CONSTRAINT
IX_Citations_CitationNumber UNIQUE CLUSTERED (CitationNumber DESC)我可以在CitationNumber上添加索引
var indexAttr = new IndexAttribute("IX_Citations_CitationNumber")
{
IsClustered = true,
IsUnique = true,
Order = 1
};
Property(c => c.CitationNumber)
.HasColumnAnnotation("Index", new IndexAnnotation(indexAttr))但是我怎样才能消除对Id的限制呢?有可能吗?
发布于 2014-07-29 03:45:28
不,您不能这样做,即使在sql中也是如此。检查documentation。
创建主键会自动创建相应的唯一索引、聚集索引或非聚集索引。
您可以做的是将索引添加到另一列,但您不能阻止EF在主键列上创建索引。
下面是如何使用fluent api或attribute添加另一个索引。
modelBuilder.Entity<TheEntity>()
.Property(e => e.TheProperty)
.HasColumnAnnotation("IndexName", new IndexAnnotation(new IndexAttribute { IsUnique = true })));或
[Index("IndexName", IsUnique = true)]
public int TheProperty { get; set; }PS:但您可以稍后使用sql查询删除索引。
发布于 2016-06-22 20:09:45
对于EF7,这已经变得很容易了。您可以将以下选项与haskey选项一起使用。
ForSqlServerIsClustered(false); 我们可以像这样使用它
supplierItemEntity.HasKey(supplierItem => supplierItem.SupplierItemId).ForSqlServerIsClustered(false);
supplierItemEntity.HasIndex(s => new { s.ItemId }).ForSqlServerIsClustered(true).HasName("IX_SupplierItem_ItemId");

https://stackoverflow.com/questions/25002394
复制相似问题