【问题标题】:SqlClient.SqlException: Invalid column name ClassNameId While fetching data from Fluent APISqlClient.SqlException:从 Fluent API 获取数据时列名 ClassNameId 无效
【发布时间】:2019-11-13 18:53:46
【问题描述】:

我是这个 EF 的新手,我正在尝试从 Sql Db 表中获取数据,它给了我类似 invalid classNameId error. 的错误

public class ClassName
{
        [Key]
        [Display(Name = "Id:")]
        public int Id { get; set; }

        [Display(Name = "Created By:")]
        [Required(ErrorMessage = "Please enter created by.")]
        [StringLength(5, MinimumLength = 2)]
        public string CreatedBy { get; set; }
        public List<OtherClass> OtherClassList{ get; set; }
}

public class OtherClass
{

        [Column("Control")]
        [Display(Name = "Control:")]
        public String Control { get; set; }

        [ForeignKey("PID")]
        [Column("PID")]
        [Display(Name = "PID:")]
        public int PID{ get; set; }
}

数据库上下文:

protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<ClassName>()
                .HasKey(p => p.Id);

            modelBuilder.Entity<OtherClass>()
            .HasKey(p=> new { p.Control, p.PID});
}

我使用 Fluent API 从 MSSql 获取数据。

【问题讨论】:

  • EF CoreEF 6.x?
  • EF Core @AliBahrami
  • 有一个原因 classNameId 存在于您的数据表中,但数据模型类中缺少该字段,因此请先验证它。
  • 不,数据表中没有任何列以及名为 ClassNameId 的数据模型。它只是数据模型和数据表中的 ID @KalpeshBoghara
  • 所以请分享完整的错误信息。可能是你错过了什么,

标签: c# sql entity-framework entity-framework-core ef-fluent-api


【解决方案1】:

问题是这里的ForeignKey注解无效

[ForeignKey("PID")]
[Column("PID")]
[Display(Name = "PID:")]
public int PID{ get; set; }

ForeignKey 是令人困惑的属性,因为它会根据应用的位置改变参数的含义。当应用于 FK 属性时,它指示导航属性的名称。当应用于导航属性时,它表示 FK 属性的名称。

在您的情况下,它应用于 FK 属性,但指定了相同的属性名称,因此它被简单地忽略,EF 使用与 List&lt;OtherClass&gt; OtherClassList 关系关联的 FK 属性的默认常规名称,这就是您的原因获取不存在的列。

要解决此问题,请将该属性应用于其他类的导航属性(因为您在需要 FK 的类中没有导航属性):

[ForeignKey(nameof(OtherClass.PID))]
public List<OtherClass> OtherClassList{ get; set; }

或(最好)使用 fluent API 配置它:

modelBuilder.Entity<ClassName>()
    .HasMany(e => e.OtherClassList)
    .WithOne()
    .HasForeignKey(e => e.PID);

如果你有引用导航属性,除了上面的数据标注方案,你还可以使用

    [ForeignKey(nameof(ClassName))]
    [Column("PID")]
    [Display(Name = "PID:")]
    public int PID{ get; set; }

    [ForeignKey(nameof(PID))]
    public ClassName ClassName { get; set; }

或者 Fluent API .WithOne() 必须更改为 .WithOne(e =&gt; e.ClassName)

【讨论】:

  • 我已经尝试过使用您的 fluent API 解决方案,现在它给我的错误是 Invalid column name ClassNameId1, 以前是 ClassNameId
  • 帖子中的课程没有办法。很可能您确实OtherClass 中有指向ClassName(类似于public ClassName ClassName { get; set; })的参考导航属性未在帖子中显示,不是吗?如果是这样,只需在 WithOne 中指定它,例如.WithOne(e =&gt; e.ClassName)。请在问题中包含所有相关属性(即使它们不是真实模型,我们也能理解)。关系流式 API 必须完全匹配任一侧导航属性的存在/不存在。
  • 是的,我有一个属性 public ClassName ClassName { get;放; }) 在我的课堂上,只是在添加代码时忽略了这一点。
  • 你不应该。因为这样做会打开其他可能的 ForeignKey 属性解决方案,并更改流式 API 解决方案。这些小细节非常重要。为了清楚起见,让我更新答案。
猜你喜欢
  • 2019-10-17
  • 1970-01-01
  • 1970-01-01
  • 2021-05-27
  • 2020-11-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-09
相关资源
最近更新 更多