Search code examples
asp.netentity-framework-4

how to fix EntityReference error


I'm attempt to commit mostly all new objects to the database, apart from the user. I'm new to entity framework and im not sure how to combat this error.

Error on line _orderDetail.CalenderItems.Add(_newCalendarItem):

The object could not be added or attached because its EntityReference has an EntityKey property value that does not match the EntityKey for this object.

Code:

 _db.Orders.AddObject(_order)
        For Each n In _namelist
            _db.Names.AddObject(n)
        Next
        For Each n In _namelist
            For i As Integer = 1 To _copies
                Dim _orderDetail As New OrderDetail
                _db.OrderDetails.AddObject(_orderDetail)
                _orderDetail.Name = n
                _orderDetail.Order = _order
                For Each c In _calendarItems
                    Dim _newCalendarItem As New CalenderItem
                    _newCalendarItem.Image = c.Image
                    _newCalendarItem.YearMonth = c.YearMonth
                    _orderDetail.CalenderItems.Add(_newCalendarItem)
                Next
            Next
        Next
        _db.SaveChanges()

I believe I need to add add an entity reference but I'm not sure how. Can anyone point me in the right direction


Solution

  • As dnndeveloper says, your answer is ObjectContext.CreateObject<T>.

    So you're gonna want -

     Dim ci = _db.CreateObject(Of CalenderItem)()
     ci.OrderDetail = _orderDetail
     ci.Image = c.image
     ci.YearMonth = c.YearMonth
    
     _orderDetail.CalenderItems.Add(ci)
    

    or something along those lines. I've run into this issue a couple of times and this has worked so far.

    HTH