FreeSql icon indicating copy to clipboard operation
FreeSql copied to clipboard

如何使用 Code First 的 Fluent API 方式定义表字段信息?

Open zfchai opened this issue 2 years ago • 3 comments

  • FreeSql 使用 code first 的 Fluent API 方式
 fsql.CodeFirst.ApplyConfiguration(new SongConfiguration());
  • Song 实体模型定义和 SongConfiguration
// 实体模型类举例
public class Song
{
    /// <summary>
    /// 主键,必填
    /// </summary>
    public Guid Id { get; set; }
    /// <summary>
    /// Title,必填
    /// </summary>
    public string Title { get; set; } = string.Empty;
    /// <summary>
    /// Url,必填
    /// </summary>
    public string Url { get; set; } = string.Empty;
    /// <summary>
    /// CreateTime,必填
    /// </summary>
    public DateTime CreateTime { get; set; }
    /// <summary>
    /// TypeId,必填
    /// </summary>
    public string TypeId { get; set; } = string.Empty;
    /// <summary>
    /// Field1, 可选
    /// </summary>
    public string? Field1 { get; set; }
    /// <summary>
    /// RowVersion,必填
    /// </summary>
    public long RowVersion { get; set; }
}

public class SongConfiguration : IEntityTypeConfiguration<Song>
{
    public void Configure(EfCoreTableFluent<Song> eb)
    {
         eb.ToTable("tb_song");
         /* 
          * 其他字段按照上面的注释具体该怎么描写,并且可以在数据库表中生成对应字段的备注描述。
          * 其次,字段命名在数据库可自定义,比如:RowVersion 字段,在数据库表中列名 row_version  
          */
    }
}

SongConfiguration 继承 IEntityTypeConfiguration<Song> 对象,在 Configure 方法中关于实体对象的表结构定义特性该怎么写,有参考文档说明麽?谢谢!

zfchai avatar May 07 '24 07:05 zfchai

注释就用///<summary>写是最合适的,不仅能生成数据库备注,也方便别人使用这个类

如果只是RowVersion 字段 转换成row_version 不需要主动写任何特性,可以在定义FreeSqlBuilder时指定UseNameConvert参数 如

 .UseNameConvert(NameConvertType.PascalCaseToUnderscoreWithLower)

可以看FluentApi文档,配置具体的内容: https://freesql.net/guide/fluent-api.html#entity

比如,使用.Help()方法后可使用和特性标签同样的配置项

   builder.Property(rt => rt.LockoutEnd).Help().Name("");

luoyunchong avatar May 15 '24 05:05 luoyunchong

感谢你的解答,我还想知道定义表结构,使用 Fluent API 风格模式,在 Configure 方法中 eb 具体使用参考有文档麽?

zfchai avatar May 17 '24 04:05 zfchai

这个? https://github.com/dotnetcore/FreeSql/wiki/FluentApi#%E5%AE%9E%E4%BD%93%E9%85%8D%E7%BD%AE%E7%B1%BB

pjy612 avatar May 17 '24 10:05 pjy612