Entity Framework 保存基础时出错 class 如果有任何继承

Entity Framework errors while saving base class if there is any inheritance

我正在使用 EF 6.1。我有一个模型 "Request" 直接从我的数据库中通过向导构建。在我的上下文文件 (EMContext.vb) 中,我有

Public Overridable Property Requests As DbSet(Of Request)

当我输入时

        Dim db As New EMContext
    Dim req As New Request()
    With req
        .RequestedBy = "bar"
        .EventName = "Goo"
        .RequestedOn = Now
        .RequestStatusID = 1
    End With

    db.Requests.Add(req)
    db.SaveChanges()

一切都按预期进行。没问题。它节省了。 但是,如果我添加 class(应用程序中的任何位置)

    Class foo
       Inherits Request

       Public Property s As String
    End Class

然后 运行 我得到的完全相同的代码

{"An error occurred while updating the entries. See the inner exception for details."}

查看内部异常:

{"Invalid column name 's'. Invalid column name 'Discriminator'."}

为什么它甚至查看继承的 class 属性? 顺便说一句,如果我从继承的 class 中删除所有属性,我仍然会收到无效列 'Discriminator' 错误。

然后创建一个自定义 class,json 将解析到该自定义 class,然后您可以调用实体并从该 class 生成它。

<Serializable()>
Public Class jSonParsedObject
  'properties that match the Entity object
  'custom properties you need for other work
End Class

用法:

Dim jsonObj As jSonParsedObject = SomeMethodThatParsesAndReturnsData()
Dim req As New Request()
With req
    .RequestedBy = jsonObj.RequestedBy
    .EventName = jsonObj.EventName
    .RequestedOn = jsonObj.RequestedOn
    .RequestStatusID = jsonObj.RequestStatusID
End With
...