【问题标题】:I get a invalid column name exception while accessing a Entity field访问实体字段时出现无效的列名异常
【发布时间】:2018-12-31 12:40:56
【问题描述】:

我最近在 Course 表中添加了一个名为“CreatedBy”的列,它引用了数据库中用户表中的 UserID 并为其创建了相应的实体字段。但是在访问 CreatedBy 字段时出现错误: System.Data.SqlClient.SqlException:列名“CreatedByID”无效。

我尝试了不同的数据注释方式,但没有奏效。

实体:

public partial class Course
{
    public Course()
    {
        this.CourseLessons = new List<CourseLesson>();
    }

    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int CourseID { get; set; }
    public string CourseName { get; set; }
    public string CourseDescription { get; set; }        
    public int? CreatedByID { get; set; }

    [ForeignKey("CreatedByID")]
    public virtual WebsiteUser CreatedBy { get; set; }
    public virtual ICollection<CourseLesson> CourseLessons { get; set; }
}

public partial class WebsiteUser
{
    public WebsiteUser()
    {
        // Other code
    }
    [Key]
    public int UserID { get; set; }

    [Required]
    public string Name { get; set; }

    [Required]
    public string Email { get; set; }
}

public ActionResult EditCourse()
{
    SQLContext context = new SQLContext();
    var deletethis = context.Courses.First().CreatedBy;  // Gives error
    return View(context.Courses);
}

【问题讨论】:

  • 您的实体类型是什么?数据库优先还是代码优先?你更新你的数据库和迁移了吗?

标签: c# entity-framework model-view-controller foreign-keys


【解决方案1】:

“CreatedByID”是数据库表列的默认约定名称,对应于您在此处映射为外键的CreatedByID 属性

public int? CreatedByID { get; set; }

[ForeignKey("CreatedByID")]
public virtual WebsiteUser CreatedBy { get; set; }

为了更改常规列名,您可以使用[Column] 数据注释(属性):

[Column("CreatedBy")]
public int? CreatedByID { get; set; }

或流畅的 API:

modelBuilder.Entity<Course>()
    .Property(e => e.CreatedById)
    .HasColumnName("CreatedBy");

概括地说,ForeignKey 属性指定要映射为 FK 列的 实体属性的名称,而 Column 属性指定 表列的名称映射到该属性。

【讨论】:

    【解决方案2】:

    尝试使用单引号

    '

    改为双引号

    "

    它在 Postgresql 数据库中对我有用。

    例如

    [ForeignKey('CreatedByID')]
    

    【讨论】:

    • 为什么要这样做?你试过了吗?
    • 如果你试过了,你就不会叫别人试试了。
    • 这甚至为你编译了吗?我猜如果它没有编译,那么你也没有进入运行时异常部分,因此问题在某种意义上解决了?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-07
    • 2022-07-04
    • 2014-07-13
    • 1970-01-01
    • 2013-01-02
    • 2011-12-08
    相关资源
    最近更新 更多