11using System ;
2+ using System . Collections . Generic ;
3+ using System . ComponentModel . DataAnnotations . Schema ;
24using System . Data . Entity . Core . Metadata . Edm ;
35using System . Data . Entity . Infrastructure ;
6+ using System . Data . Entity . Infrastructure . Annotations ;
47using System . Data . Entity . ModelConfiguration . Conventions ;
8+ using System . Linq ;
59
610namespace SQLite . CodeFirst . Convention
711{
812 public class SqliteForeignKeyIndexConvention : IStoreModelConvention < AssociationType >
913 {
14+ private const string IndexAnnotationName = "http://schemas.microsoft.com/ado/2013/11/edm/customannotation:Index" ;
15+
1016 public virtual void Apply ( AssociationType item , DbModel model )
1117 {
1218 if ( item == null )
@@ -21,6 +27,44 @@ public virtual void Apply(AssociationType item, DbModel model)
2127 {
2228 return ;
2329 }
30+
31+ for ( int i = 0 ; i < item . Constraint . ToProperties . Count ; i ++ )
32+ {
33+ EdmProperty edmProperty = item . Constraint . ToProperties [ i ] ;
34+ var annotation = GetAnnotation ( edmProperty . MetadataProperties , IndexAnnotationName ) ;
35+ if ( annotation != null )
36+ {
37+ // The original attribute is removed. The noneForeignKeyIndicies will be remained and readded without any modification
38+ // and the foreignKeyIncidies will be readded with the correct name.
39+ edmProperty . RemoveAnnotation ( IndexAnnotationName ) ;
40+
41+ var noneForeignKeyIndicies = annotation . Indexes . Where ( index => index . Name != "IX_" + edmProperty . Name ) ;
42+ IndexAnnotation newIndexAnnotation = new IndexAnnotation ( noneForeignKeyIndicies ) ;
43+
44+ var foreignKeyIndicies = annotation . Indexes . Where ( index => index . Name == "IX_" + edmProperty . Name ) ;
45+ foreach ( var foreignKeyIndex in foreignKeyIndicies )
46+ {
47+ var indexAttribute = new IndexAttribute ( string . Format ( "IX_{0}_{1}" , item . Constraint . ToRole . Name , edmProperty . Name ) ) ;
48+ IndexAnnotation foreignKeyIndexAnnotation = new IndexAnnotation ( indexAttribute ) ;
49+ newIndexAnnotation = ( IndexAnnotation ) newIndexAnnotation . MergeWith ( foreignKeyIndexAnnotation ) ;
50+ }
51+
52+ edmProperty . AddAnnotation ( IndexAnnotationName , newIndexAnnotation ) ;
53+ }
54+ }
55+ }
56+
57+
58+ private static IndexAnnotation GetAnnotation ( IEnumerable < MetadataProperty > metadataProperties , string name )
59+ {
60+ foreach ( MetadataProperty metadataProperty in metadataProperties )
61+ {
62+ if ( metadataProperty . Name . Equals ( name , StringComparison . Ordinal ) )
63+ {
64+ return ( IndexAnnotation ) metadataProperty . Value ;
65+ }
66+ }
67+ return null ;
2468 }
2569 }
2670}
0 commit comments