Skip to content

Commit 89c174a

Browse files
committed
Issue_21: Added logic to SqliteForeignKeyIndexConvention.
Todo: - Encapsulate index name generation - More Column indicies
1 parent cf0b63c commit 89c174a

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

SQLite.CodeFirst/Convention/SqliteForeignKeyIndexConvention.cs

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,18 @@
11
using System;
2+
using System.Collections.Generic;
3+
using System.ComponentModel.DataAnnotations.Schema;
24
using System.Data.Entity.Core.Metadata.Edm;
35
using System.Data.Entity.Infrastructure;
6+
using System.Data.Entity.Infrastructure.Annotations;
47
using System.Data.Entity.ModelConfiguration.Conventions;
8+
using System.Linq;
59

610
namespace 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

Comments
 (0)