[entity framework core] Entity Framework Core Property Configuration
https://www.learnentityframeworkcore.com/configuration/fluent-api/property-configuration
配置entity的属性是非常之常用的, 我们可以为属性进行长度等各方面的限制, 都可以使用 fluent 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 | 
- example
 
    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; }
    }

                
            
        
浙公网安备 33010602011771号