EF Core数据注解是用于实体类和属性的特性,支持表名、主键、字段约束、关系及忽略字段等配置;适合中小型项目,高级功能需配合Fluent API使用。

EF Core 数据注解(Data Annotations)是一组写在实体类和属性上的特性(Attributes),让 EF Core 在运行时自动理解如何把你的 C# 类映射到数据库表结构、字段约束、关系等。它简单直观,适合中小型项目或快速原型开发。
用 [Table] 指定实体映射的数据库表名,可选带 Schema:
[Table("users", Schema = "auth")]
public class User
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
}users 表;加 Schema = "auth" 则生成在 auth.users 下Id 或 ClassNameId,但显式标注更清晰可靠对字符串等属性加验证和数据库约束注解:
public class Product
{
[Key]
public int Id { get; set; }
<pre class="brush:php;toolbar:false;">[Required] // NOT NULL
[MaxLength(100)] // nvarchar(100)
public string Name { get; set; }
[Column(TypeName = "decimal(18,2)")]
public decimal Price { get; set; }
[StringLength(500)]
public string Description { get; set; }}
NOT NULL 列varchar、datetime2、decimal(18,2)
用 [ForeignKey] 明确声明外键属性,并配合导航属性使用:
public class Order
{
public int Id { get; set; }
public int CustomerId { get; set; }
<pre class="brush:php;toolbar:false;">[ForeignKey("CustomerId")]
public Customer Customer { get; set; }}
public class Customer
{
public int Id { get; set; }
public string Name { get; set; }
public List
Customer 导航属性由 CustomerId 字段驱动CustomerId 对应 Customer),可省略该注解;但显式写上更易维护[ForeignKey] 参数是外键属性名(字符串),不是导航属性名用 [NotMapped] 排除不存入数据库的字段:
public class User
{
public int Id { get; set; }
public string Email { get; set; }
<pre class="brush:php;toolbar:false;">[NotMapped]
public string DisplayName => $"User-{Email.Split('@')[0]}";
[NotMapped]
public DateTime LocalCreatedAt { get; set; }}
get only)、只写属性(set only)基本上就这些。数据注解够用、轻量、易读,但不支持复合主键、复杂索引、继承映射等高级功能——那些得靠 Fluent API。日常开发中,建议先用注解搭骨架,再按需用 OnModelCreating 补充细节。
以上就是EF Core Data Annotations怎么用 EF Core数据注解使用方法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号