How do I remove underscore of foreign key fields in code first by convention

前端 未结 7 932
傲寒
傲寒 2020-11-30 01:20

I\'ve got multiple classes (including TPT) in my project. Each POCO has a BaseClass, which has a GUID (called GlobalKey) as primary ke

7条回答
  •  执笔经年
    2020-11-30 01:43

    I had issues when combining it with an id naming convention of EntityNameId.

    When using the following convention to ensure the Customer table has CustomerId rather than simply Id.

    modelBuilder.Properties()
                            .Where(p => p.Name == "Id")
                            .Configure(p => p.IsKey().HasColumnName(p.ClrPropertyInfo.ReflectedType == null ? "Id" : p.ClrPropertyInfo.ReflectedType.Name +"Id"));
    

    The foreign key naming convention needs to be changed to the following.

     /// 
        /// Provides a convention for fixing the independent association (IA) foreign key column names.
        /// 
        public class ForeignKeyNamingConvention : IStoreModelConvention
        { 
            public void Apply(AssociationType association, DbModel model) 
            { 
                // Identify ForeignKey properties (including IAs)  
                if (!association.IsForeignKey) return;
    
                // rename FK columns  
                var constraint = association.Constraint; 
                if (DoPropertiesHaveDefaultNames(constraint.FromProperties, constraint.ToProperties)) 
                { 
                    NormalizeForeignKeyProperties(constraint.FromProperties); 
                } 
    
                if (DoPropertiesHaveDefaultNames(constraint.ToProperties, constraint.FromProperties)) 
                { 
                    NormalizeForeignKeyProperties(constraint.ToProperties); 
                }
            } 
    
            private static bool DoPropertiesHaveDefaultNames(IReadOnlyList properties, IReadOnlyList otherEndProperties) 
            { 
                if (properties.Count != otherEndProperties.Count) 
                { 
                    return false; 
                } 
    
                for (var i = 0; i < properties.Count; ++i)
                {
                    if (properties[i].Name.Replace("_", "") != otherEndProperties[i].Name) 
                    { 
                        return false; 
                    } 
                } 
    
                return true; 
            } 
    
            private void NormalizeForeignKeyProperties(ReadOnlyMetadataCollection properties) 
            { 
                for (var i = 0; i < properties.Count; ++i) 
                { 
                    var underscoreIndex = properties[i].Name.IndexOf('_'); 
                    if (underscoreIndex > 0) 
                    { 
                        properties[i].Name = properties[i].Name.Remove(underscoreIndex, 1); 
                    }                 
                } 
            } 
        }
    

提交回复
热议问题