【问题标题】:The property is not a declared property on type 'class'该属性不是“类”类型的声明属性
【发布时间】:2021-01-26 20:58:59
【问题描述】:

我收到错误The property 'Rank' is not a declared property on type 'MasterUser'. Verify that the property has not been explicitly excluded from the model by using the Ignore method or NotMappedAttribute data annotation. Make sure that it is a valid primitive property. 我检查了我的模型类,它就在那里。

public class MasterUser
{
    //many other properties...
    public virtual char Rank { get; set; }
    //more properties below
}

我还检查了我的数据库上下文,它也在那里并且完美映射。

public class BBDataContext : DbContext
{
    public DbSet<MasterUser> Users { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        #region MUSR_USRID mapping

        //Mapped properties above....
        modelBuilder.Entity<MasterUser>()
            .Property(usr => usr.Rank).HasColumnName("MUSR_RANK");
        //More mapped properties..

        modelBuilder.Entity<MasterUser>().ToTable("dbo.MUSR_FIL");
        #endregion

        base.OnModelCreating(modelBuilder);
    }
}

在表中,MUSR_RANK 可以为 char 数据类型为空。

我该如何解决这个问题?数据库对此有影响吗?我目前使用的是 SQL Server 2000。

感谢您的帮助。

【问题讨论】:

    标签: c# entity-framework ef-code-first


    【解决方案1】:

    Primitive Data Types Supported in the Entity Data Model

    所以我认为你必须使用string 而不是char

    并在OnModelCreating中添加一些数据

    modelBuilder.Entity<MasterUser>()
                .Property(usr => usr.Rank).HasColumnName("MUSR_RANK")
                .HasMaxLength(1)
                .IsFixedLength()
                .IsUnicode(false);
    

    【讨论】:

    • 这会影响从 EF 传递到数据库的数据吗?比如,它会自动将数据库中的string从EF转换为char吗?
    • @Musikero31 是的,有了 Max 和 Fixed 长度的控制,你应该没有任何问题。
    • 所以你的意思是即使MUSR_RANK的数据类型在数据库中是char,EF也会很容易的将映射类型字符串转换为char对吧?
    • @Musikero31 这就是我所说的,但它应该不难测试,不是吗?还是您遇到了问题?
    • 我认为这将在同一时间。但仍需检查。谢谢!
    【解决方案2】:

    当我找到此页面时,我遇到了同样的错误并正在寻求帮助。我知道这篇文章很旧,但由于我的解决方案不同,我发布它以防它帮助其他人。我正在使用 EF 6。

    我的错误是因为我无意中将模型类的属性设为只读。

    [Key]
    [StringLength(10)]
    public string ProjectNumber { get; }
    

    EF 错误并不能很好地描述问题。一旦我添加了 set 访问器,错误就消失了。

    【讨论】:

      猜你喜欢
      • 2015-07-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-26
      • 2022-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多