c# - EF 随机看到错误的属性类型

标签 c# entity-framework exception mapping

我们首先将 EF 代码与 EF 6.1.3 和 SimpleInjector 3.1.0 一起使用,我们会随机获得与此类似的异常:

The 'IsDeleted' property on 'Location' could not be set to a 'System.Int32' value. You must set this property to a non-null value of type 'System.Boolean'.
at System.Data.Entity.Core.Common.Internal.Materialization.Shaper.ErrorHandlingValueReader`1.GetValue(DbDataReader reader, Int32 ordinal)
at System.Data.Entity.Core.Common.Internal.Materialization.Shaper.GetPropertyValueWithErrorHandling[TProperty](Int32 ordinal, String propertyName, String typeName)
at lambda_method(Closure , Shaper )
at System.Data.Entity.Core.Common.Internal.Materialization.Coordinator`1.ReadNextElement(Shaper shaper)
at System.Data.Entity.Core.Common.Internal.Materialization.Shaper`1.SimpleEnumerator.MoveNext()
at System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable`1 source)

在这种情况下,Location 表的 IsDeleted 列是位/非空。 Location 实体上的 Property 绝对是一个不可为 null 的 bool 值。我已经检查了我们的 git 存储库中实体的整个历史记录,这个属性除了 bool 值之外什么都不是,而且服务器上的当前 dll 是正确的,所以问题不是由错误的代码引起的/

真正奇怪的是,我们的网站大部分时间都运行良好,我希望每次都会出现这种异常。更奇怪的是,我们已经看到同样类型的错误发生在其他 3 个实体上(似乎也是随机发生的)。在每种情况下,它都是不同的属性和数据类型。 例如:

The 'Description' property on 'SysGroup' could not be set to a 'System.Boolean' value. You must set this property to a non-null value of type 'System.Int32'.

The 'SysGroupId' property on 'SysInfo' could not be set to a 'System.String' value. You must set this property to a non-null value of type 'System.Int32'.

The 'Id' property on 'BaseEntity' could not be set to a 'System.Guid' value. You must set this property to a non-null value of type 'System.Int32'.

关于最后一个......我们拥有的每个实体都继承自 BaseEntity,它有一个名为“Id”的不可为 null 的 int 属性。我们也不在任何地方使用任何 Guid。因此,如果 BaseEntity 确实为 Id 属性使用了 Guid,那么任何地方的每个查询都会失败。最后一个异常发生在代码导航属性时,如下所示:

var desc = SysInfoInstance.SysGroup.Description;

有什么想法吗?

Location 类本质上是:

public class Location : 
    BaseEntity
{
    ...
    public virtual bool IsDeleted { get; set; }
}
public abstract class BaseEntity
{
    public virtual int Id { get; set; }
}

最佳答案

我不确定为什么您的 IsDeleted 属性被标记为虚拟。

没有其他理由使属性虚拟化。导航属性标记为虚拟以用于延迟加载,标量属性标记为虚拟以用于更改跟踪。

IsDeleted 不需要虚拟关键字

您可以如下创建另一个属性,而不是将其映射到您的数据库。但这不是必需的。

public int Deleted { get; set; }

[System.ComponentModel.DataAnnotations.Schema.NotMapped]
public bool IsDeleted
{
    get { return Deleted == 1; }
    set { Deleted = value ? 1 : 0; }
}

关于c# - EF 随机看到错误的属性类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35011086/

相关文章:

c# - 将 Entity Framework 从 MVC 移动到另一个项目会导致重新迁移

c# - 如何在单元测试中模拟在随机代码点抛出异常?

c# - 删除数据表中的行 -> DeletedRowInaccessible

python - Python 中的类型及其可见性之间的差异

线程完成后C#更新UI

c# - 避免两次 WPF 打开同一个窗口

entity-framework - 任何指向 DbSet 属性名称的信息吗?

c# - C# 属性声明的键盘快捷方式?

c# - 删除 taghelper 生成的输入标签中的前缀

c# - Entity Framework 和 friend 数据库的问题