1, define the profile nodes, nodes or attributes can be changed according to their own situation
<configuration> <CustomAssemblySection> <assemblies> <add name="Seven.Core.Models"></add> </assemblies> </CustomAssemblySection> </configuration>
2, self-defined node configuration files, inherit ConfigurationSection
public class CustomAssemblySection : ConfigurationSection { [ConfigurationProperty("assemblies", IsDefaultCollection = false)] [ConfigurationCollection(typeof(CustomAssemblyCollection))] public CustomAssemblyCollection Assemblies { get { return (CustomAssemblyCollection)base["assemblies"]; } } }
3, custom configured child nodes inherit ConfigurationElementCollection
public class CustomAssemblyCollection : ConfigurationElementCollection { protected override ConfigurationElement CreateNewElement() { return new CustomAssemblyElement(); } protected override object GetElementKey(ConfigurationElement element) { return ((CustomAssemblyElement)element).Name; } public CustomAssemblyElement this[int Index] { get { return (CustomAssemblyElement)BaseGet(Index); } set { if (BaseGet(Index) != null) { BaseRemoveAt(Index); } BaseAdd(Index, value); } } new public CustomAssemblyElement this[string Name] { get { return (CustomAssemblyElement)BaseGet(Name); } } }
4, configuration property name
public class CustomAssemblyElement : ConfigurationElement { [ConfigurationProperty("name", IsRequired = true)] public string Name { get { return (string)this["name"]; } set { this["name"] = value; } } }
5, in the configuration file to configure, CustomAssemblySeciton custom, type fill assembly defined
<configSections> <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 --> <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" /> <section name="CustomAssemblySection" type=" Seven.Component.Data.EntityAssist.CustomAssemblySection,Seven.Component.Data"/> </configSections>
6, the rewriting Contenxt OnModelCreating method (Table following code determines whether the attribute is reflected, can be defined according to their own situation)
protected override void OnModelCreating(DbModelBuilder modelBuilder) { CustomAssemblySection configSection = (CustomAssemblySection)System.Configuration.ConfigurationManager.GetSection("CustomAssemblySection"); foreach (CustomAssemblyElement customAssembly in configSection.Assemblies) { Assembly assembly = Assembly.Load(customAssembly.Name); foreach (Type type in assembly.ExportedTypes) { var tableattrd = type.GetCustomAttribute(typeof(TableAttribute)); if (tableattrd != null && type.IsClass) { MethodInfo method = modelBuilder.GetType().GetMethod("Entity"); method = method.MakeGenericMethod(new Type[] { type }); method.Invoke(modelBuilder, null); } } } base.OnModelCreating(modelBuilder); }