流式接口

FreeSql 提供使用 Fluent Api, 在外部配置实体的数据库特性,Fluent Api 的方法命名与特性名保持一致,如下:

  1. fsql.CodeFirst
  2. .ConfigEntity<TestFluenttb1>(a =>
  3. {
  4. a.Name("xxdkdkdk1");
  5. a.Property(b => b.Id).Name("Id22").IsIdentity(true);
  6. a.Property(b => b.name).DbType("varchar(100)").IsNullable(true);
  7. })
  8. .ConfigEntity<TestFluenttb2>(a =>
  9. {
  10. a.Name("xxdkdkdk2");
  11. a.Property(b => b.Id).Name("Id22").IsIdentity(true);
  12. a.Property(b => b.name).DbType("varchar(100)").IsNullable(true);
  13. });
  14. //以下为实体类
  15. class TestFluenttb1 {
  16. public int Id { get; set; }
  17. public string name { get; set; } = "defaultValue";
  18. }
  19. [Table(Name = "cccccdddwww")]
  20. class TestFluenttb2 {
  21. public int Id { get; set; }
  22. public string name { get; set; } = "defaultValue";
  23. }

fsql 是一个 IFreeSql 对象

这段配置尽量只执行一次,避免性能损耗

参考:《实体特性说明》

FreeSql.DbContext v1.4.0+ 实现了 EfCore FluentApi 99% 相似的语法

  1. fsql.CodeFirst.Entity<Song>(eb => {
  2. eb.ToTable("tb_song");
  3. eb.Ignore(a => a.Field1);
  4. eb.Property(a => a.Title).HasColumnType("varchar(50)").IsRequired();
  5. eb.Property(a => a.Url).HasMaxLength(100);
  6. eb.Property(a => a.RowVersion).IsRowVersion();
  7. eb.Property(a => a.CreateTime).HasDefaultValueSql("current_timestamp");
  8. eb.HasKey(a => a.Id);
  9. eb.HasIndex(a => new { a.Id, a.Title }).IsUnique().HasName("idx_xxx11");
  10. //一对多、多对一
  11. eb.HasOne(a => a.Type).HasForeignKey(a => a.TypeId).WithMany(a => a.Songs);
  12. //多对多
  13. eb.HasMany(a => a.Tags).WithMany(a => a.Songs, typeof(Song_tag));
  14. });
  15. fsql.CodeFirst.Entity<SongType>(eb => {
  16. eb.HasMany(a => a.Songs).WithOne(a => a.Type).HasForeignKey(a => a.TypeId);
  17. eb.HasData(new[]
  18. {
  19. new SongType
  20. {
  21. Id = 1,
  22. Name = "流行",
  23. Songs = new List<Song>(new[]
  24. {
  25. new Song{ Title = "真的爱你" },
  26. new Song{ Title = "爱你一万年" },
  27. })
  28. },
  29. new SongType
  30. {
  31. Id = 2,
  32. Name = "乡村",
  33. Songs = new List<Song>(new[]
  34. {
  35. new Song{ Title = "乡里乡亲" },
  36. })
  37. },
  38. });
  39. });
  40. public class SongType {
  41. public int Id { get; set; }
  42. public string Name { get; set; }
  43. public List<Song> Songs { get; set; }
  44. }
  45. public class Song {
  46. [Column(IsIdentity = true)]
  47. public int Id { get; set; }
  48. public string Title { get; set; }
  49. public string Url { get; set; }
  50. public DateTime CreateTime { get; set; }
  51. public int TypeId { get; set; }
  52. public SongType Type { get; set; }
  53. public int Field1 { get; set; }
  54. public long RowVersion { get; set; }
  55. }

优先级

数据库特性 > 实体特性 > FluentApi(配置特性) > Aop(配置特性)