static void Test() { ICodeFirst cf = null; cf.Entity <Song>(eb => { eb.ToTable("tb_song"); eb.Ignore(a => a.Field1); eb.Property(a => a.Title).HasColumnType("varchar(50)").IsRequired(); eb.Property(a => a.Url).HasMaxLength(100); eb.Property(a => a.RowVersion).IsRowVersion(); eb.Property(a => a.CreateTime).HasDefaultValueSql("getdate()"); eb.HasKey(a => a.Id); eb.HasIndex(a => a.Title).IsUnique().HasName("idx_xxx11"); //一对多、多对一 eb.HasOne(a => a.Type).HasForeignKey(a => a.TypeId).WithMany(a => a.Songs); //多对多 eb.HasMany(a => a.Tags).WithMany(a => a.Songs, typeof(Song_tag)); }); cf.Entity <SongType>(eb => { eb.HasMany(a => a.Songs).WithOne(a => a.Type).HasForeignKey(a => a.TypeId); }); }
/// <summary> /// EFCore 95% 相似的 FluentApi 扩展方法 /// </summary> /// <param name="codeFirst"></param> /// <param name="entityType">实体类型</param> /// <param name="modelBuilder"></param> /// <returns></returns> public static ICodeFirst Entity(this ICodeFirst codeFirst, Type entityType, Action <EfCoreTableFluent> modelBuilder) { var cf = codeFirst as CodeFirstProvider; codeFirst.ConfigEntity(entityType, tf => modelBuilder(new EfCoreTableFluent(cf._orm, tf, entityType))); return(codeFirst); }
public static void ConfigEntity(this ICodeFirst codeFirst, IModel efmodel) { foreach (var type in efmodel.GetEntityTypes()) { codeFirst.ConfigEntity(type.ClrType, a => { //表名 var relationalTableName = type.FindAnnotation("Relational:TableName"); if (relationalTableName != null) { a.Name(relationalTableName.Value?.ToString() ?? type.ClrType.Name); } foreach (var prop in type.GetProperties()) { var freeProp = a.Property(prop.Name); //列名 var relationalColumnName = prop.FindAnnotation("Relational:ColumnName"); if (relationalColumnName != null) { freeProp.Name(relationalColumnName.Value?.ToString() ?? prop.Name); } //主键 freeProp.IsPrimary(prop.IsPrimaryKey()); //自增 freeProp.IsIdentity( prop.ValueGenerated == ValueGenerated.Never || prop.ValueGenerated == ValueGenerated.OnAdd || prop.GetAnnotations().Where(z => z.Name == "SqlServer:ValueGenerationStrategy" && z.Value.ToString().Contains("IdentityColumn") || //sqlserver 自增 z.Value.ToString().Contains("IdentityColumn") //其他数据库实现未经测试 ).Any() ); //可空 freeProp.IsNullable(prop.GetAfterSaveBehavior() != PropertySaveBehavior.Throw); //类型 var relationalColumnType = prop.FindAnnotation("Relational:ColumnType"); if (relationalColumnType != null) { var dbType = relationalColumnType.ToString(); if (!string.IsNullOrEmpty(dbType)) { var maxLength = prop.FindAnnotation("MaxLength"); if (maxLength != null) { dbType += $"({maxLength})"; } freeProp.DbType(dbType); } } } }); } }
public static ICodeFirst ApplyConfiguration <TEntity>(this ICodeFirst codeFirst, IEntityTypeConfiguration <TEntity> configuration) where TEntity : class { return(codeFirst.Entity <TEntity>(eb => { configuration.Configure(eb); })); }
/// <summary> /// 初始化数据 /// </summary> /// <param name="codeFirst">ICodeFirst对象</param> /// <param name="isSyncData">是否初始化数据</param> /// <returns>返回ICodeFirst对象</returns> public static ICodeFirst SeedData(this ICodeFirst codeFirst, bool isSyncData) { if (!isSyncData) { return(codeFirst); } //初始化用户数据 codeFirst.Entity <User>(e => { e.HasData(new List <User> { new User { UserName = "******", NikeName = "管理员", Email = "*****@*****.**", Mobile = "18655556666", Password = EncryptHelper.Md5By32("superadmin"), CreateTime = DateTime.Now }, new User { UserName = "******", NikeName = "自研", Email = "*****@*****.**", Mobile = "18655556667", Password = EncryptHelper.Md5By32("ioself"), CreateTime = DateTime.Now } }); }); return(codeFirst); }
public TableFluent(ICodeFirst codeFirst, Type entityType, TableAttribute table) { _codeFirst = codeFirst; _entityType = entityType; _properties = _entityType.GetPropertiesDictIgnoreCase(); _table = table; }
/// <summary> /// EFCore 95% 相似的 FluentApi 扩展方法 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="codeFirst"></param> /// <param name="modelBuilder"></param> /// <returns></returns> public static ICodeFirst Entity <T>(this ICodeFirst codeFirst, Action <EfCoreTableFluent <T> > modelBuilder) { var cf = codeFirst as CodeFirstProvider; codeFirst.ConfigEntity <T>(tf => modelBuilder(new EfCoreTableFluent <T>(cf._orm, tf))); return(codeFirst); }
public static void EfCoreFluentApiTestDynamic(this ICodeFirst cf) { cf.Entity(typeof(Song), eb => { eb.ToTable("tb_song2"); eb.Ignore("Field1"); eb.Property("Title").HasColumnType("varchar(50)").IsRequired(); eb.Property("Url").HasMaxLength(100); eb.Property("RowVersion").IsRowVersion(); eb.Property("CreateTime").HasDefaultValueSql("current_timestamp"); eb.HasKey("Id"); eb.HasIndex("Title").IsUnique().HasName("idx_tb_song2222"); //一对多、多对一 eb.HasOne("Type").HasForeignKey("TypeId").WithMany("Songs"); //多对多 eb.HasMany("Tags").WithMany("Songs", typeof(Song_tag)); }); cf.Entity(typeof(SongType), eb => { eb.ToTable("tb_songtype2"); eb.HasMany("Songs").WithOne("Type").HasForeignKey("TypeId"); eb.HasData(new[] { new SongType { Id = 1, Name = "流行", Songs = new List <Song>(new[] { new Song { Title = "真的爱你" }, new Song { Title = "爱你一万年" }, }) }, new SongType { Id = 2, Name = "乡村", Songs = new List <Song>(new[] { new Song { Title = "乡里乡亲" }, }) }, }); }); cf.SyncStructure <SongType>(); cf.SyncStructure <Song>(); }
public static void EfCoreFluentApiTestGeneric(this ICodeFirst cf) { cf.Entity <Song>(eb => { eb.ToTable("tb_song1"); eb.Ignore(a => a.Field1); eb.Property(a => a.Title).HasColumnType("varchar(50)").IsRequired(); eb.Property(a => a.Url).HasMaxLength(100); eb.Property(a => a.RowVersion).IsRowVersion(); eb.Property(a => a.CreateTime).HasDefaultValueSql("current_timestamp"); eb.HasKey(a => a.Id); eb.HasIndex(a => a.Title).IsUnique().HasName("idx_tb_song1111"); //一对多、多对一 eb.HasOne(a => a.Type).HasForeignKey(a => a.TypeId).WithMany(a => a.Songs); //多对多 eb.HasMany(a => a.Tags).WithMany(a => a.Songs, typeof(Song_tag)); }); cf.Entity <SongType>(eb => { eb.ToTable("tb_songtype1"); eb.HasMany(a => a.Songs).WithOne(a => a.Type).HasForeignKey(a => a.TypeId); eb.HasData(new[] { new SongType { Id = 1, Name = "流行", Songs = new List <Song>(new[] { new Song { Title = "真的爱你" }, new Song { Title = "爱你一万年" }, }) }, new SongType { Id = 2, Name = "乡村", Songs = new List <Song>(new[] { new Song { Title = "乡里乡亲" }, }) }, }); }); cf.SyncStructure <SongType>(); cf.SyncStructure <Song>(); }
protected override void OnModelCreating(ICodeFirst codefirst) { codefirst.Entity <Song>(eb => { eb.ToTable("tb_song"); eb.Ignore(a => a.Field1); eb.Property(a => a.Title).HasColumnType("varchar(50)").IsRequired(); eb.Property(a => a.Url).HasMaxLength(100); eb.Property(a => a.RowVersion).IsRowVersion(); eb.Property(a => a.CreateTime).HasDefaultValueSql("current_timestamp"); eb.HasKey(a => a.Id); eb.HasIndex(a => new { a.Id, a.Title }).IsUnique().HasName("idx_xxx11"); //一对多、多对一 eb.HasOne(a => a.Type).HasForeignKey(a => a.TypeId).WithMany(a => a.Songs); //多对多 eb.HasMany(a => a.Tags).WithMany(a => a.Songs, typeof(Song_tag)); }); codefirst.Entity <SongType>(eb => { eb.HasMany(a => a.Songs).WithOne(a => a.Type).HasForeignKey(a => a.TypeId); eb.HasData(new[] { new SongType { Id = 1, Name = "流行", Songs = new List <Song>(new[] { new Song { Title = "真的爱你" }, new Song { Title = "爱你一万年" }, }) }, new SongType { Id = 2, Name = "乡村", Songs = new List <Song>(new[] { new Song { Title = "乡里乡亲" }, }) }, }); }); codefirst.SyncStructure <SongType>(); codefirst.SyncStructure <Song>(); }
/// <summary> /// 映射配置 /// </summary> /// <param name="modelBuilder">模型生成器</param> public void Map(ICodeFirst modelBuilder) { ModelBuilder = modelBuilder; modelBuilder.Entity <TEntity>(builder => { MapTable(builder); }); }
public MsAccessProvider(string masterConnectionString, string[] slaveConnectionString, Func <DbConnection> connectionFactory = null) { this.InternalCommonUtils = new MsAccessUtils(this); this.InternalCommonExpression = new MsAccessExpression(this.InternalCommonUtils); this.Ado = new MsAccessAdo(this.InternalCommonUtils, masterConnectionString, slaveConnectionString, connectionFactory); this.Aop = new AopProvider(); this.CodeFirst = new MsAccessCodeFirst(this, this.InternalCommonUtils, this.InternalCommonExpression); }
public SqliteProvider(string masterConnectionString, string[] slaveConnectionString) { this.InternalCommonUtils = new SqliteUtils(this); this.InternalCommonExpression = new SqliteExpression(this.InternalCommonUtils); this.Ado = new SqliteAdo(this.InternalCommonUtils, masterConnectionString, slaveConnectionString); this.Aop = new AopProvider(); this.CodeFirst = new SqliteCodeFirst(this, this.InternalCommonUtils, this.InternalCommonExpression); }
/// <summary> /// 映射配置 /// </summary> /// <param name="modelBuilder">模型生成器</param> public void Map(ICodeFirst modelBuilder) { ModelBuilder = modelBuilder; modelBuilder.Entity <TEntity>(builder => { MapTable(builder); MapVersion(builder); MapProperties(builder); MapAssociations(builder); }); }
protected override void OnModelCreating(ICodeFirst codefirst) { codefirst.ConfigEntity <Models.T_User>(builder => { builder.Property(i => i.DeptId).StringLength(32); builder.Navigate(i => i.T_Dept, nameof(T_User.DeptId)); }); codefirst.ConfigEntity <Models.T_Dept>(builder => { builder.Navigate(i => i.T_User, null); }); }
public static ICodeFirst SeedData(this ICodeFirst fsql) { fsql.Entity <RoleEntity>(e => { e.HasData(new List <RoleEntity>() { new RoleEntity(RoleEntity.Admin, "管理员", true, 1), new RoleEntity(RoleEntity.User, "用户", true, 1) }); }); return(fsql); }
public SqliteProvider(string masterConnectionString, string[] slaveConnectionString, Func <DbConnection> connectionFactory = null) { this.InternalCommonUtils = new SqliteUtils(this); this.InternalCommonExpression = new SqliteExpression(this.InternalCommonUtils); this.Ado = new SqliteAdo(this.InternalCommonUtils, masterConnectionString, slaveConnectionString, connectionFactory); this.Aop = new AopProvider(); this.CodeFirst = new SqliteCodeFirst(this, this.InternalCommonUtils, this.InternalCommonExpression); if (connectionFactory != null) { this.CodeFirst.IsNoneCommandParameter = true; } }
public SqliteProvider(IDistributedCache cache, ILogger log, string masterConnectionString, string[] slaveConnectionString) { if (log == null) { log = new LoggerFactory(new[] { new Microsoft.Extensions.Logging.Debug.DebugLoggerProvider() }).CreateLogger("FreeSql.Sqlite"); } this.InternalCommonUtils = new SqliteUtils(this); this.InternalCommonExpression = new SqliteExpression(this.InternalCommonUtils); this.Cache = new CacheProvider(cache, log); this.Ado = new SqliteAdo(this.InternalCommonUtils, this.Cache, log, masterConnectionString, slaveConnectionString); this.CodeFirst = new SqliteCodeFirst(this, this.InternalCommonUtils, this.InternalCommonExpression); }
/// <summary> /// 生成一个普通访问功能的 IFreeSql 对象,用来访问 odbc /// </summary> /// <param name="masterConnectionString"></param> /// <param name="slaveConnectionString"></param> /// <param name="adapter">适配器</param> public OdbcProvider(string masterConnectionString, string[] slaveConnectionString) { this.InternalCommonUtils = new OdbcUtils(this); this.InternalCommonExpression = new OdbcExpression(this.InternalCommonUtils); this.Ado = new OdbcAdo(this.InternalCommonUtils, masterConnectionString, slaveConnectionString); this.Aop = new AopProvider(); this.CodeFirst = new OdbcCodeFirst(this, this.InternalCommonUtils, this.InternalCommonExpression); var _utils = InternalCommonUtils as OdbcUtils; //处理 MaxLength this.Aop.ConfigEntityProperty += new EventHandler <Aop.ConfigEntityPropertyEventArgs>((s, e) => { object[] attrs = null; try { attrs = e.Property.GetCustomAttributes(false).ToArray(); //.net core 反射存在版本冲突问题,导致该方法异常 } catch { } var maxlenAttr = attrs.Where(a => { return(((a as Attribute)?.TypeId as Type)?.Name == "MaxLengthAttribute"); }).FirstOrDefault(); if (maxlenAttr != null) { var lenProp = maxlenAttr.GetType().GetProperties().Where(a => a.PropertyType.IsNumberType()).FirstOrDefault(); if (lenProp != null && int.TryParse(string.Concat(lenProp.GetValue(maxlenAttr, null)), out var tryval)) { if (tryval != 0) { switch (this.Ado.DataType) { case DataType.Sqlite: e.ModifyResult.DbType = tryval > 0 ? $"{_utils.Adapter.MappingOdbcTypeVarChar}({tryval})" : _utils.Adapter.MappingOdbcTypeText; break; } } } } }); }
public static ICodeFirst GetCodeFirst(ConnectionConfig currentConnectionConfig) { ICodeFirst result = CreateInstance <ICodeFirst>(GetClassName(currentConnectionConfig.DbType.ToString(), "CodeFirst")); return(result); }
/// <summary> /// 设置实体属性 /// </summary> /// <param name="codeFirst">ICodeFirst对象</param> /// <returns>返回ICodeFirst对象</returns> public static ICodeFirst ConfigEntity(this ICodeFirst codeFirst) { return(codeFirst); }
protected override void OnModelCreating(ICodeFirst codefirst) { codefirst.IsLazyLoading = true; base.OnModelCreating(codefirst); }
public static ICodeFirst SeedData(this ICodeFirst @this) { @this.Entity <LinGroup>(e => { e.HasData(new List <LinGroup>() { new LinGroup(LinGroup.Admin, "系统管理员", true), new LinGroup(LinGroup.CmsAdmin, "CMS管理员", true), new LinGroup(LinGroup.User, "普通用户", true) }); }) .Entity <LinUser>(e => { e.HasData(new List <LinUser>() { new LinUser() { Nickname = "系统管理员", Username = "******", Active = UserActive.Active, CreateTime = DateTime.Now, IsDeleted = false, LinUserIdentitys = new List <LinUserIdentity>() { new LinUserIdentity(LinUserIdentity.Password, "admin", EncryptUtil.Encrypt("123qwe"), DateTime.Now) }, LinUserGroups = new List <LinUserGroup>() { new LinUserGroup(1, LinConsts.Group.Admin) }, }, new LinUser() { Nickname = "CMS管理员", Username = "******", Active = UserActive.Active, CreateTime = DateTime.Now, IsDeleted = false, LinUserIdentitys = new List <LinUserIdentity>() { new LinUserIdentity(LinUserIdentity.Password, "CmsAdmin", EncryptUtil.Encrypt("123qwe"), DateTime.Now) }, LinUserGroups = new List <LinUserGroup>() { new LinUserGroup(2, LinConsts.Group.CmsAdmin) }, } }); }) .Entity <BaseType>(e => { e.HasData(new List <BaseType>() { new BaseType("Article.Type", "文章类型", 1) { CreateTime = DateTime.Now, IsDeleted = false, CreateUserId = 1, BaseItems = new List <BaseItem>() { new BaseItem("0", "原创", 1, 1, true) { CreateUserId = 1, CreateTime = DateTime.Now, IsDeleted = false }, new BaseItem("1", "转载", 2, 1, true) { CreateUserId = 1, CreateTime = DateTime.Now, IsDeleted = false }, new BaseItem("2", "翻译", 3, 1, true) { CreateUserId = 1, CreateTime = DateTime.Now, IsDeleted = false } } }, new BaseType("Sex", "性别", 2) { CreateTime = DateTime.Now, IsDeleted = false, CreateUserId = 1, BaseItems = new List <BaseItem>() { new BaseItem("0", "男", 1, 2, true) { CreateTime = DateTime.Now, IsDeleted = false }, new BaseItem("1", "女", 2, 2, true) { CreateTime = DateTime.Now, IsDeleted = false }, new BaseItem("2", "保密", 3, 2, true) { CreateTime = DateTime.Now, IsDeleted = false } } }, }); }) ; return(@this); }
/// <summary> /// 同步结构到数据中 /// </summary> /// <param name="codeFirst"></param> private static void SyncStruct(ICodeFirst codeFirst) { // codeFirst.SyncStructure(typeof(user)); }
/// <summary> /// 根据Assembly扫描所有继承IEntityTypeConfiguration<T>的配置类 /// </summary> /// <param name="codeFirst"></param> /// <param name="assembly"></param> /// <param name="predicate"></param> /// <returns></returns> public static ICodeFirst ApplyConfigurationsFromAssembly(this ICodeFirst codeFirst, Assembly assembly, Func <Type, bool> predicate = null) { IEnumerable <TypeInfo> typeInfos = assembly.DefinedTypes.Where(t => !t.IsAbstract && !t.IsGenericTypeDefinition); MethodInfo methodInfo = typeof(FreeSqlDbContextExtensions).Assembly.GetExtensionMethods(typeof(ICodeFirst)) .Single((e) => e.Name == "Entity" && e.ContainsGenericParameters); if (methodInfo == null) { return(codeFirst); } foreach (TypeInfo constructibleType in typeInfos) { if (constructibleType.GetConstructor(Type.EmptyTypes) == null || predicate != null && !predicate(constructibleType)) { continue; } foreach (var @interface in constructibleType.GetInterfaces()) { if (@interface.IsGenericType && @interface.GetGenericTypeDefinition() == typeof(IEntityTypeConfiguration <>)) { var type = @interface.GetGenericArguments().First(); var efFluentType = typeof(EfCoreTableFluent <>).MakeGenericType(type); var actionType = typeof(Action <>).MakeGenericType(efFluentType); //1.需要实体和Configuration配置 //codeFirst.Entity<ToDoItem>(eb => //{ // new ToDoItemConfiguration().Configure(eb); //}); //2.需要实体 //Action<EfCoreTableFluent<ToDoItem>> x = new Action<EfCoreTableFluent<ToDoItem>>(e => //{ // object o = Activator.CreateInstance(constructibleType); // constructibleType.GetMethod("ApplyConfiguration")?.Invoke(o, new object[1] { e }); //}); //codeFirst.Entity<ToDoItem>(x); //3.实现动态调用泛型委托 DelegateBuilder delegateBuilder = new DelegateBuilder(constructibleType); MethodInfo applyconfigureMethod = delegateBuilder.GetType().GetMethod("ApplyConfiguration")?.MakeGenericMethod(type); if (applyconfigureMethod == null) { continue; } Delegate @delegate = Delegate.CreateDelegate(actionType, delegateBuilder, applyconfigureMethod); methodInfo.MakeGenericMethod(type).Invoke(null, new object[2] { codeFirst, @delegate }); } } } return(codeFirst); }
public static ICodeFirst SeedData(this ICodeFirst fsql) { fsql.Entity <UserEntity>(e => { e.HasData(new List <UserEntity>() { new UserEntity() { Nickname = "超级管理员", Username = "******", CreateTime = DateTime.Now, IsDeleted = false, UserIdentitys = new List <UserIdentityEntity>() { new UserIdentityEntity(UserIdentityEntity.Password, "administrator", EncryptUtil.Encrypt("123456"), DateTime.Now) }, UserRoles = new List <UserRoleEntity>() { new UserRoleEntity(1, SystemConst.Role.Administrator) }, }, new UserEntity() { Nickname = "管理员", Username = "******", CreateTime = DateTime.Now, IsDeleted = false, UserIdentitys = new List <UserIdentityEntity>() { new UserIdentityEntity(UserIdentityEntity.Password, "administrator", EncryptUtil.Encrypt("123456"), DateTime.Now) }, UserRoles = new List <UserRoleEntity>() { new UserRoleEntity(2, SystemConst.Role.Admin) }, } }); }) .Entity <RoleEntity>(e => { e.HasData(new List <RoleEntity>() { new RoleEntity(RoleEntity.Administrator, "超级管理员", true, 1), new RoleEntity(RoleEntity.Admin, "普通管理员", true, 1), new RoleEntity(RoleEntity.User, "普通用户", true, 1) }); }) .Entity <BaseTypeEntity>(e => { e.HasData(new List <BaseTypeEntity>() { new BaseTypeEntity("Statement.Type", "账目类型", 1) { CreateTime = DateTime.Now, IsDeleted = false, CreateUserId = 1, BaseItems = new List <BaseItemEntity>() { new BaseItemEntity("0", "支出", 1, true, 1) { CreateUserId = 1, CreateTime = DateTime.Now, IsDeleted = false }, new BaseItemEntity("1", "收入", 2, true, 1) { CreateUserId = 1, CreateTime = DateTime.Now, IsDeleted = false }, new BaseItemEntity("2", "转账", 3, true, 1) { CreateUserId = 1, CreateTime = DateTime.Now, IsDeleted = false }, new BaseItemEntity("3", "还款", 3, true, 1) { CreateUserId = 1, CreateTime = DateTime.Now, IsDeleted = false } } }, new BaseTypeEntity("Sex", "性别", 2) { CreateTime = DateTime.Now, IsDeleted = false, CreateUserId = 1, BaseItems = new List <BaseItemEntity>() { new BaseItemEntity("0", "未知", 1, true, 2) { CreateTime = DateTime.Now, IsDeleted = false }, new BaseItemEntity("1", "男", 2, true, 2) { CreateTime = DateTime.Now, IsDeleted = false }, new BaseItemEntity("2", "女", 3, true, 2) { CreateTime = DateTime.Now, IsDeleted = false } } }, }); }); return(fsql); }
public static ICodeFirst Entity <T>(this ICodeFirst codeFirst, Action <EfCoreTableFluent <T> > modelBuilder) { codeFirst.ConfigEntity <T>(tf => modelBuilder(new EfCoreTableFluent <T>(tf))); return(codeFirst); }