标签:attribute rop csharp component 程序 int builder ase work
1、配置文件中定义节点,可根据 自己的情况更改节点或属性
<configuration>
<CustomAssemblySection>
<assemblies>
<add name="Seven.Core.Models"></add>
</assemblies>
</CustomAssemblySection>
</configuration>
2、自定义配置文件的节点,继承ConfigurationSection
public class CustomAssemblySection : ConfigurationSection
{
[ConfigurationProperty("assemblies", IsDefaultCollection = false)]
[ConfigurationCollection(typeof(CustomAssemblyCollection))]
public CustomAssemblyCollection Assemblies
{
get
{
return (CustomAssemblyCollection)base["assemblies"];
}
}
}
3、自定配置子节点,继承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、配置属性名称
public class CustomAssemblyElement : ConfigurationElement
{
[ConfigurationProperty("name", IsRequired = true)]
public string Name
{
get
{
return (string)this["name"];
}
set
{
this["name"] = value;
}
}
}
5、在配置文件中配置,CustomAssemblySeciton为自定义,type填写定义的程序集
<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、重写Contenxt中的OnModelCreating方法(以下代码判断是否有Table属性的进行反射,可根据自己情况定义)
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);
}
【.Net】使用配置文件 DbContext 动态加载 DbSet
标签:attribute rop csharp component 程序 int builder ase work
原文地址:https://www.cnblogs.com/Seven77yixuan/p/10966676.html