EF 6 新特性一
介绍
接下来我将给大家重点介绍一下.Net 6 之后的一些新的变更,文章都是来自于外国大佬的文章,我这边进行一个翻译,并加上一些自己的理解和解释。
源作者链接:https://blog.okyrylchuk.dev/entity-framework-core-6-features-part-1#heading-1-unicode-attribute
正文
Unicode 属性
EF Core 6.0 中的新 Unicode 属性允许您将字符串属性映射到非 Unicode 列,而无需直接指定数据库类型。当数据库系统仅支持 Unicode 类型时,忽略 Unicode 属性。
public class Book
{
public int Id { get; set; }
public string Title { get; set; }
[Unicode(false)]
[MaxLength(22)]
public string Isbn { get; set; }
}
迁移:
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Books",
columns: table => new
{
Id = table.Column(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Title = table.Column(type: "nvarchar(max)", nullable: true),
Isbn = table.Column(type: "varchar(22)", unicode: false, maxLength: 22, nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Books", x => x.Id);
});
}
精度属性
在 EF Core 6.0 之前,您可以使用 Fluent API 配置精度和规模。现在,您还可以使用具有新属性 Precision 的数据注释来做到这一点。
public class Product
{
public int Id { get; set; }
[Precision(precision: 10, scale: 2)]
public decimal Price { get; set; }
}
迁移:
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Products",
columns: table => new
{
Id = table.Column(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Price = table.Column(type: "decimal(10,2)", precision: 10, scale: 2, nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Products", x => x.Id);
});
}
EntityTypeConfiguration 属性
从 EF Core 6.0 开始,您可以在实体类型上放置一个新的 EntityTypeConfiguration 属性,以便 EF Core 可以找到并使用适当的配置。在此之前,必须实例化类配置并从OnModelCreating方法调用。
public class ProductConfiguration : IEntityTypeConfiguration
{
public void Configure(EntityTypeBuilder builder)
{
builder.Property(p => p.Name).HasMaxLength(250);
builder.Property(p => p.Price).HasPrecision(10, 2);
}
}
[EntityTypeConfiguration(typeof(ProductConfiguration))]
public class Product
{
public int Id { get; set; }
public decimal Price { get; set; }
public string Name { get; set; }
}
结语
联系作者:加群:867095512 @MrChuJiu