# NetCoreCodeSnippet **Repository Path**: ssawk/NetCoreCodeSnippet ## Basic Information - **Project Name**: NetCoreCodeSnippet - **Description**: 记录一些 .Net Core 的代码片段 - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 2 - **Forks**: 0 - **Created**: 2019-04-09 - **Last Updated**: 2022-11-22 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # efCore CodeSnippet #### 介绍 记录一下代码片段 #### 模型属性 ``` #排除类型&属性 [NotMapped] #主键 [Key] #必选属性 [Required] #最大长度 [MaxLength(500)] #乐观锁时间戳 [Timestamp] public byte[] Timestamp { get; set; } #值转换(枚举转字符串) [Column(TypeName = "nvarchar(24)")] public enum Type{ get; set; } #注释 [Comment("表注释")] public class Blog { [Comment("列注释")] public int BlogId { get; set; } public string Url { get; set; } } #列名 [Column("blog_id")] public int BlogId { get; set; } ``` #### Fluent API ``` #索引(非唯一) modelBuilder.Entity() .HasIndex(b => b.Url); #索引(唯一) modelBuilder.Entity() .HasIndex(b => b.Url) .IsUnique(); #索引(联合) modelBuilder.Entity() .HasIndex(p => new { p.FirstName, p.LastName }); #备用键 modelBuilder.Entity() .HasAlternateKey(p => new { p.FirstName, p.LastName }); #默认值 modelBuilder.Entity() .Property(b => b.Created) .HasDefaultValueSql("getdate()"); #查询筛选 modelBuilder.Entity().HasQueryFilter(p => !p.IsDeleted); #值转换 var converter = new EnumToStringConverter(); modelBuilder .Entity() .Property(e => e.Mount) .HasConversion(converter); ``` #### DataAnnotations ``` #显示名 [Display(Name = "标题")] #必填 [Required(ErrorMessage = "{0}不能为空")] #sql类型 [Column(TypeName = "nvarchar(400)")] #范围 [Range(0, int.MaxValue, ErrorMessage = "{0}大于等于0")] #最大字符 [MaxLength(50, ErrorMessage = "{0}不超过{1}个字")] ``` #### 命令 ``` #迁移 dotnet ef migrations add goodsv8 -c DbCore.xxxx.xxxContext #更新 dotnet ef database update -c DbCore.xxxx.xxxContext ```