Entity Framework Code First Fluent Api: Adding Indexes to columns

前端 未结 15 1379
一生所求
一生所求 2020-11-30 17:43

I\'m running EF 4.2 CF and want to create indexes on certain columns in my POCO objects.

As an example lets say we have this employee class:

public c         


        
15条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-30 18:07

    To build further on all these great responses, we added the following code to enable the Index attribute to be picked up from an associated metadata type. For the full details please see my blog post, but in summary here are the details.

    Metadata types are used like this:

        [MetadataType(typeof(UserAccountAnnotations))]
        public partial class UserAccount : IDomainEntity
            {
            [Key]
            public int Id { get; set; } // Unique ID
            sealed class UserAccountAnnotations
                {
                [Index("IX_UserName", unique: true)]
                public string UserName { get; set; }
                }
           }
    

    In this example the metadata type is a nested class, but it doesn't have to be, it can be any type. Property matching is done by name only, so the metadata type just has to have a property of the same name, and any data annotations applied to that should then be applied to the associated entity class. This didn't work in the original solution because it doesn't check for the associated metadata type. We plumbed in the following helper method:

    /// 
    ///   Gets the index attributes on the specified property and the same property on any associated metadata type.
    /// 
    /// The property.
    /// IEnumerable{IndexAttribute}.
    IEnumerable GetIndexAttributes(PropertyInfo property)
        {
        Type entityType = property.DeclaringType;
        var indexAttributes = (IndexAttribute[])property.GetCustomAttributes(typeof(IndexAttribute), false);
        var metadataAttribute =
            entityType.GetCustomAttribute(typeof(MetadataTypeAttribute)) as MetadataTypeAttribute;
        if (metadataAttribute == null)
            return indexAttributes; // No metadata type
    
        Type associatedMetadataType = metadataAttribute.MetadataClassType;
        PropertyInfo associatedProperty = associatedMetadataType.GetProperty(property.Name);
        if (associatedProperty == null)
            return indexAttributes; // No metadata on the property
    
        var associatedIndexAttributes =
            (IndexAttribute[])associatedProperty.GetCustomAttributes(typeof(IndexAttribute), false);
        return indexAttributes.Union(associatedIndexAttributes);
        }
    

提交回复
热议问题