【问题标题】:ASP.NET MVC - Can't set overrideable property = nothing?ASP.NET MVC - 无法设置可覆盖属性 = 什么都没有?
【发布时间】:2012-06-06 03:39:06
【问题描述】:

假设我有以下实体:

Public Class Dodo
    Public Property ID As Integer

    Public Property Name As String

    Public Overridable Property Mother As DodoMother
End Class

Public Class DodoMother
    Public Property ID As Integer

    Public Property Name As String

    Public Property Age As Integer
End Class

我需要能够在设置后将 Dodo.Mother 设置为空。

Dim ndodo as dodo = db.Dodos.find(1)
ndodo.Mother = nothing
db.SaveChanges()

当我执行上述代码时,我没有收到错误或异常或任何表明该语句无效的情况。 ndodo 对象似乎没有将 Mother 设置为 null,并且 DB 没有得到更新。

我做错了吗? 我也尝试添加 db.Entry(ndodo).State = EntityState.Modified 但这也不起作用。

【问题讨论】:

    标签: asp.net-mvc vb.net asp.net-mvc-3 entity-framework


    【解决方案1】:

    您需要为 DodoMother 向 Dodo 添加一个 Id 属性并将其设置为空。

    Public Property MotherId as Integer?
    

    您的“母亲”属性是 Navagation 属性。导航属性不是数据库表的一部分,它们是实体类的一部分。

    【讨论】:

      【解决方案2】:

      谢谢JLH :)

      Public Property MotherID() As Nullable(Of Integer)
      
      Public Overridable Property Mother() As DodoMother
      

      和下面的代码删除Mother

      Dim ndodo as dodo = db.Dodos.find(1)
      ndodo.MotherID = nothing
      db.SaveChanges()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-07-16
        • 2016-07-29
        • 2015-11-04
        • 2014-10-02
        相关资源
        最近更新 更多