mrtaikandi
mrtaikandi

Reputation: 6948

Setting PK is clustered using EF6 fluent api

It's been bugging me that I have to use migration to set a primary key to not clustered but I'm not able to use fluent API to set it.

Is there any way/hack to extend fluent API to support setting primary key IsClustered property in a way that when we add a migration the generated C# code shows a correct implementation too?

Upvotes: 0

Views: 966

Answers (2)

shanavascet
shanavascet

Reputation: 589

For EF 7 it has been made easy. You can use the following option with the haskey option.

ForSqlServerIsClustered(false); 

we can use it like

supplierItemEntity.HasKey(supplierItem => supplierItem.SupplierItemId).ForSqlServerIsClustered(false);

 supplierItemEntity.HasIndex(s => new { s.ItemId }).ForSqlServerIsClustered(true).HasName("IX_SupplierItem_ItemId");

enter image description here

Upvotes: 1

Gert Arnold
Gert Arnold

Reputation: 109080

The fluent API is mainly targeted at mapping, not database design. I think it should stay that way. API's shouldn't mix concerns. Rules concerning clustered indexes don't belong in a mapping API. It has no bearing on a mapping whether an index is clustered or not. Moreover the rules on clustered indexes are database-specific, so they can be only be implemented in a Provider. But the mapping API has no knowledge of any provider.

In my personal opinion, even the IndexAttribute (introduced in EF 6.1) was an insensible compromise. (Although apparently it preluded on mapping foreign key associations to unique indexes, which will be supported in EF7).

Conversely, the HasKey method, although deeply involved in database design rules too, does make sense, because EF needs to know an entity's primary key. It's pivotal in all CRUD actions. And 'primary key' is a concept that all RDBMS vendors share.

Upvotes: 1

Related Questions