实体框架5正在发送错误的数据

时间:2013-06-25 21:29:20

标签: vb.net entity-framework-5

我有一个非常严重的问题,EF发回错误的数据。我知道它的错误,因为我可以对管理工作室中的同一个表运行相同的查询,并获得完全不同的结果。

我研究了这个问题,发现有些人能够通过添加以下内容来解决问题:

*DbContextSummary.Refresh(RefreshMode.StoreWins, result);*

当我尝试添加时,我收到此错误:

  

要刷新的对象集合中索引0处的元素具有空EntityKey属性值,或者未附加到此ObjectStateManager。

我收到错误后尝试:DbContextSummary.Attach(结果),我收到了另一个错误。

什么是正确的解决方案,为什么会发生这种情况?

相关代码(没有刷新调用):

Private _dbContextSummary As BudgetEntities

     Public ReadOnly Property DbContextSummary() As BudgetEntities
            Get
                If _dbContextSummary Is Nothing Then
                    _dbContextSummary = New BudgetEntities
                End If
                Return _dbContextSummary
            End Get
        End Property

     <WebMethod()> _
        Public Function GetSummaryData(ByVal month As String, ByVal year As String, ByVal expenseLine As String, ByVal organization As String) As List(Of SummaryModel)
            Dim result As List(Of SummaryModel) = Nothing

result = (From s In DbContextSummary.FPRs _
                    Where s.FY = year _
                    Where s.Month = month _
                    Where s.FPRLine = expenseLine _
                    Where s.VP = organization
                    Group s By s.MgrID, s.ProgAdm, s.FinanceNumber, s.FinanceNumberName Into g = Group _
                    Order By g.FirstOrDefault.MgrLastName, g.FirstOrDefault.ProgAdm Ascending
                    Select New SummaryModel With { _
                        .Actual = g.Sum(Function(a) a.Actual), _
                        .Plan = g.Sum(Function(p) p.Plan), _
                        .YTDActual = g.Sum(Function(ya) ya.YTDActual), _
                        .YTDPlan = g.Sum(Function(yp) yp.YTDPlan), _
                        .FinanceNumber = g.FirstOrDefault.FinanceNumber, _
                        .FinanceNumberName = g.FirstOrDefault.FinanceNumberName, _
                        .MgrLastName = g.FirstOrDefault.MgrLastName + ", " + g.FirstOrDefault.MgrFirstName, _
                        .PlanYearTotal = g.FirstOrDefault.PlanYearTotal, _
                        .ProgAdm = g.FirstOrDefault.ProgAdm _
                        }).ToList()
Return result
    End Function

1 个答案:

答案 0 :(得分:1)

  

什么是正确的解决方案,为什么会发生这种情况?

简而言之,您的方案中没有适当的解决方案。在对不是实体的类型(Refresh)执行投影(select new)后,SummaryModel完全不适用。您的result集合不包含SummaryModel个实体。您既不能将Refresh也不会Attach应用于此集合或其元素。这两种方法都适用于模型实体:Refresh从数据存储中更新已经连接的实体的属性,Attach将实体添加到状态{{1 }}

我建议您打开一个新问题并说明为什么您认为“ EF发送错误的数据”并尝试解决问题。当加载传递错误结果时,重新加载不太可能提供正确的数据。