https://www.learnentityframeworkcore.com/configuration/fluent-api/property-configurationexpress
配置entity的屬性是很是之經常使用的, 咱們能夠爲屬性進行長度等各方面的限制, 均可以使用 fluent api完成, 下面表格列出的是一些 api:api
method | des |
---|---|
HasAnnotation | Provides a means to apply annotations via the Fluent API |
HasColumnName | Specifies the name of the database column that the property should map to |
HasColumnType | Specifies the data type of the database column that the property should map to |
HasDefaultValue | Configures the default value of the database column that the property maps to |
HasDefaultValueSql | Configures the default value expression for the database column that the property maps to |
HasMaxLength | Specifies maximum length of data that can be stored for strings or binary data (arrays) |
IsConcurrencyToken | Denotes that the property takes part in concurrency management |
IsRequired | Configures the database column as not nullable |
ValueGeneratedNever | Specifies that the database should not automatically generate values for the property |
ValueGeneratedOnAdd | Specifies that values should only be generated automatically when new data is added |
ValueGeneratedOnAddOrUpdate | Specifies that values should be generated automatically when data is added or updated |
public class SampleContext : DbContext { public DbSet<Book> Books { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Book>() .Property(b => b.Title).HasColumnName("Description"); modelBuilder.Entity<Book>() .Property(b => b.Title).HasColumnType("varchar"); modelBuilder.Entity<Book>() .Property(b => b.Title).HasMaxLength(150); modelBuilder.Entity<Book>() .Propery(p => p.IsActive).HasDefaultValue(true); modelBuilder.Entity<Book>() .Propery(p => p.DateCreated).HasDefaultValueSql("GetUtcDate()"); modelBuilder.Entity<Book>() .Property(p => p.BookId).ValueGeneratedNever(); } } public class Book { public int BookId { get; set; } public string Title { get; set; } public Author Author { get; set; } public bool IsActive { get; set; } public DateTime DateCreated { get; set; } }