EF 的 霸气配置,秒杀一切
Posted 吴晓阳
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了EF 的 霸气配置,秒杀一切相关的知识,希望对你有一定的参考价值。
class Program { static void Main(string[] args) { TestContext testContext = new TestContext(); ///获取数据库表Person中的所有数据 在查询的时候最好加上AsNoTracking 禁止EF跟踪 // var personList = testContext.Persons.AsNoTracking().ToList(); } } public class TestContext : DbContext { private static TestContext _instance; public static TestContext Instance { get { if (_instance == null) { _instance = new TestContext(); } return _instance; } } private string _connectionString; public string ConnectionString { get { if (string.IsNullOrWhiteSpace(_connectionString)) { _connectionString = ConfigurationManager.ConnectionStrings["testConn"].ConnectionString; } return _connectionString; } set { _connectionString = value; } } public TestContext() : base("name=testConn") { _connectionString = ConfigurationManager.ConnectionStrings["testConn"].ConnectionString; } public TestContext(string connectionString) : base(connectionString) { } protected override void OnModelCreating(DbModelBuilder modelBuilder) { ///DomainMapping 所在的程序集一定要写对,因为目前在当前项目所以是采用的当前正在运行的程序集 如果你的mapping在单独的项目中 记得要加载对应的assembly ///这是重点 var typesToRegister = Assembly.GetExecutingAssembly().GetTypes() .Where(type => !String.IsNullOrEmpty(type.Namespace)) .Where(type => type.BaseType != null && type.BaseType.BaseType != null && type.BaseType.BaseType.GetGenericTypeDefinition() == typeof(EntityTypeConfiguration<>)); foreach (var type in typesToRegister) { dynamic configurationInstance = Activator.CreateInstance(type); modelBuilder.Configurations.Add(configurationInstance); } base.OnModelCreating(modelBuilder); } } public class BaseDomain { } [Table("Person")] public class Person { public string ID { get; set; } public string Name { get; set; } public string Age { get; set; } } public class PersonMapping : BaseDomainMapping<Person> { public override void Init() { this.ToTable("Person"); this.HasKey(l => l.ID); this.Property(l => l.Name).HasMaxLength(200).IsRequired();//设置Name属性长度为200 并且是必填 this.Property(l => l.Age).HasMaxLength(200).IsOptional(); //设置Age长度为200 并且可为空 } } public abstract class BaseDomainMapping<T> : EntityTypeConfiguration<T> where T : BaseDomain, new() { public BaseDomainMapping() { Init(); } /// <summary> /// 初始化代码 /// </summary> public virtual void Init() { Console.WriteLine("Init"); } }
以上是关于EF 的 霸气配置,秒杀一切的主要内容,如果未能解决你的问题,请参考以下文章