在 C# 的 Entity Framework (EF) 中,特性(Attributes)是用来提供关于实体类及其成员的元数据信息。这些特性可以控制 EF 如何将实体映射到数据库表以及如何处理实体之间的关系。以下是一些在 Entity Framework 中常用的特性:
-
[Table]
-
指定实体类映射到数据库中的哪个表。
[Table("Customers")] public class Customer {// ... }
-
-
[Key]
-
标记实体类的主键属性。
public class Customer {[Key]public int CustomerId { get; set; }// ... }
-
-
[Column]
-
指定实体类的属性映射到数据库表中的哪个列。
public class Customer {public int CustomerId { get; set; }[Column("FirstName")]public string Name { get; set; }// ... }
-
-
[Required]
-
指定属性在数据库中对应的列不允许空值。
public class Customer {public int CustomerId { get; set; }[Required]public string Name { get; set; }// ... }
-
-
[StringLength]
-
指定字符串属性的最大长度。
public class Customer {public int CustomerId { get; set; }[StringLength(100)]public string Name { get; set; }// ... }
-
-
[ForeignKey]
-
指定导航属性的外键关系。
public class Order {[Key]public int OrderId { get; set; }[ForeignKey("CustomerId")]public int CustomerId { get; set; }public virtual Customer Customer { get; set; }// ... }
-
-
[InverseProperty]
-
指定实体间的关系的另一端。
public class Customer {[Key]public int CustomerId { get; set; }public virtual ICollection<Order> Orders { get; set; }// ... } public class Order {[Key]public int OrderId { get; set; }public int CustomerId { get; set; }[ForeignKey("CustomerId")][InverseProperty("Orders")]public virtual Customer Customer { get; set; }// ... }
-
-
[Index]
-
指定数据库中应该为该属性创建索引。
public class Customer {public int CustomerId { get; set; }[Index]public string LastName { get; set; }// ... }
-
-
[MaxLength]
-
指定字符串属性的最大长度,与
StringLength
类似,但更适用于 EF Core。
public class Customer {public int CustomerId { get; set; }[MaxLength(100)]public string Name { get; set; }// ... }
-
-
[NotMapped]
-
指定某个属性不应该映射到数据库中的列。
public class Customer {public int CustomerId { get; set; }public string Name { get; set; }[NotMapped]public string FullName { get; set; }// ... }
-
-
[Timestamp]
-
用于乐观并发控制,标记属性作为数据库行的版本号。
public class Customer {public int CustomerId { get; set; }public string Name { get; set; }[Timestamp]public byte[] RowVersion { get; set; }// ... }
-
-
[ConcurrencyCheck]
-
用于标记属性在更新时需要检查是否被并发修改。
public class Customer {public int CustomerId { get; set; }[ConcurrencyCheck]public string Name { get; set; }// ... }
-
这些特性提供了对 Entity Framework 映射和行为的细粒度控制