为了允许我们以自己的方式来创建数据库schema和映射关系,我们需要重写EF Core 默认契约,我们已经了解默认EF Core契约是如何工作的,如果我们想重写契约需要修改配置和领域类到数据库的映射
EF Core 有两种配置方法:
1 Data Annotation Attributes
2 Fluent API
1 Data Annotation Attributes
这些.NET特性能被应用到领域类的属性中,这些特性包含在单独的命名空间中System.ComponentModel.DataAnnotations
让我们通过一个例子来了解如何在领域类内使用Data Annotation 特性配置数据库表和重写默认契约在EF Core
在下面代码中我们给到2个领域类的属性提交Data Annotation Attributes (Country & City)
[Table("TBL_City")]
public class City
{
[Key]
public int KeyId { get; set; }
[Column("CityName", TypeName = "varchar(25)")]
public string Name { get; set; }
[NotMapped]
public int Population { get; set; }
[ForeignKey("FKid")]
public Country Country { get; set; }
}
[Table("TBL_Country")]
public class Country
{
[Key]
public int KeyId { get; set; }
[MaxLength(20)]
public string Name { get; set; }
}
由于在类上使用了[Table("Name")] 特性,当我们运行EF Core Migration 数据库将会创建两张表,这些表是:
1 TBL_City
2 TBL_Country
在视图的输入项中我们广泛应用了Data Annotation Attributes
TBL_City表:
1 KeyId 列作为主键
2 CityName 列使用了 varchar(25)类型
3 FKid 列作为外键
常用[NotMapped]特性告诉EF Core不会在TBL_City表中创建列
TBL_Country 表:
1 KeyId列作为主键
2 Name 列使用了类型 nvarchar(20)
下面图片显示了数据库中两张表
EF Core Data Annotations
特性 | 描述 |
---|---|
Table | 实体类映射到数据库中表的名称 |
Column | 属性映射到在表的列名称、顺序和数据类型 |
Key | 设置属性作为表的主键 |
ForeignKey | 将一个属性标记为外键 |
NotMapped | 不会在数据库的表中生成该属性对应的列 |
MaxLength | 为表列设置最大值 |
Required | 指定该属性在表中对应的列不能为空 |
2 Fluent API
可以使用EF Core Fluent API配置领域类,接下我们会写4篇文章来了解Fluent API
总结
这节我们主要学习使用Data Annotation Attributes重写默认契约
源代码地址:
https://github.com/bingbing-gui/Asp.Net-Core-Skill/tree/master/EntityFrameworkCore/EFCoreConfiguration
参考资料
https://learn.microsoft.com/en-us/ef/core/modeling/entity-types?tabs=data-annotations
https://learn.microsoft.com/en-us/ef/core/modeling/entity-properties?tabs=data-annotations%2Cwithout-nrt
https://learn.microsoft.com/en-us/ef/core/modeling/keys?tabs=data-annotations
https://www.yogihosting.com/configurations-entity-framework-core/