如果我有:
using System.ComponentModel.DataAnnotations.Schema;
namespace API.Entities
{
[Table("ProductOrders", Schema = "product_orders")]
public class ProductOrders
{
public int Id { get; set; }
public int? CategoryId { get; set; }
public Category? Category { get; set; }
}
}
如何将
Category
命名为我喜欢的任何名称?
Category
重命名为 MainCategory
第二个问题:对多个表使用同一个表,所以我可能会
secondaryCategory
引用同一个表
例如有SecondaryCategoryId 和SecondaryCategory?二级类别{获取;放; }
例如这行得通吗?
[Table("ProductOrders", Schema = "product_orders")]
public class ProductOrders
{
public int Id { get; set; }
[Column("CategoryId")]
public int? MainCategoryId { get; set; }
[ForeignKey("MainCategoryId")]
public Category? MainCategory { get; set; }
[Column("CategoryId")]
public int? SecondCategoryId { get; set; }
[ForeignKey("SecondCategoryId")]
public Category? SecondCategory { get; set; }
}
重命名
CategoryId
和Category
:参考教程:列名、ForeignKeyAttribute
例如:
[Table("ProductOrders", Schema = "product_orders")]
public class ProductOrders
{
public int Id { get; set; }
[Column("CategoryId")]
public int? MainCategoryId { get; set; }
[ForeignKey("MainCategoryId")]
public Category? MainCategory { get; set; }
}
您可以使用数据注释将 ProductOrders 类中的 Category 属性重命名为 MainCategory 和 secondaryCategory 之类的名称。具体来说,您可以使用 [Column] 属性来指定每个属性的列名称。
具体操作方法如下:
using System.ComponentModel.DataAnnotations.Schema;
namespace API.Entities
{
[Table("ProductOrders", Schema = "product_orders")]
public class ProductOrders
{
public int Id { get; set; }
// Rename CategoryId to MainCategoryId
[Column("CategoryId")]
public int? MainCategoryId { get; set; }
// Rename Category to MainCategory
[ForeignKey("MainCategoryId")]
public Category? MainCategory { get; set; }
// Add a secondary category with a new column name
[Column("SecondaryCategoryId")]
public int? SecondaryCategoryId { get; set; }
[ForeignKey("SecondaryCategoryId")]
public Category? SecondaryCategory { get; set; }
}
}