首页 > 解决方案 > 覆盖并重命名实体 ID

问题描述

我正在使用 ef 并且我的模型继承自:Entity。像这样,我的 ID 将是 model.Id。所以我想在模型和数据库中重命名它成为model.Model_Id。反正?

标签: c#entity-framework-core

解决方案


您可以将使用实体类属性名称的默认设置覆盖为不同的数据库列名称,如下所示:

using System.ComponentModel.DataAnnotations.Schema;

public class Student
{
    public int StudentID { get; set; }
     
    [Column("Name")]
    public string StudentName { get; set; }
    public DateTime? DateOfBirth { get; set; }
    public byte[] Photo { get; set; }
    public decimal Height { get; set; }
    public float Weight { get; set; }
}

上面的 StudentName 将映射到数据库中的“Name”列。您应该能够采用相同的方法将 Id 重命名为 Model_Id。

但是,正如其他人所提到的,您不能“重命名”具有不同名称的基类属性。您可以测试的一种选择是:

public class BaseClass
{
   [NotMapped]
   public int Id { get; set; }
}

public class DerivedClass
{
    public int Model_Id
    {
        get
        {
            return base.Id;
        }
        set
        {
            base.Id = value;
        }
    }
}

在这里,EF 会将 Model_Id 映射到数据库。但不将 Id 映射到数据库。


推荐阅读