I am trying to implement an attribute that I can apply to properties in my code first Entity Framework data model to indicate unique constraints that will be applied when the database is created. I have read about extracting EF table mapping information using the mapping API exposed for EF 6.1, and I have read about implementing a custom attribute to indicate which properties represent a natural key. But, unless I'm misreading the code, I think this will only work when the CLR property name (OSpace / CSpace) matches the SQL column name (SSpace). I would like to be able to include association properties (foreign keys) in my unique key like EnumList in this example:
Public Class EnumValue
Public Property EnumValueId As Integer
Public Property Sequence As Integer
Public Overridable Property Label As TranslatedString
<MaxLength(5), MyUnique()> _
Public Property Value As String
<MyUnique()> _
Public Overridable Property EnumList As EnumList
End Class
I've started with this much code, which it based on the linked article about mapping table names
Dim ws = DirectCast(context, System.Data.Entity.Infrastructure.IObjectContextAdapter).ObjectContext.MetadataWorkspace
Dim oSpace = ws.GetItemCollection(Core.Metadata.Edm.DataSpace.OSpace)
Dim entityTypes = oSpace.GetItems(Of EntityType)()
Dim entityContainer = ws.GetItems(Of EntityContainer)(DataSpace.CSpace).Single()
Dim mapping = ws.GetItems(Of EntityContainerMapping)(DataSpace.CSSpace).Single.EntitySetMappings
For Each setType In entityTypes
Dim cSpaceEntitySet = entityContainer.EntitySets.Single(Function(t) t.ElementType.Name = setType.Name)
Dim sSpaceEntitySet = mapping.Single(Function(t) t.EntitySet Is cSpaceEntitySet)
Dim tableInfo = sSpaceEntitySet.EntityTypeMappings.Single.Fragments.Single
Dim tableName = If(tableInfo.StoreEntitySet.Table, tableInfo.StoreEntitySet.Name)
Dim schema = tableInfo.StoreEntitySet.Schema
And that's enough to get the information I need about the table name, but now I need to somehow link the CLR property name to the SQL column name, and it's slow going understanding the EF metadata framework. I'm hoping that someone more familiar with it might speed things along.