How to update non-scalar entity properties in EF 4.0?

Posted by Mike on Stack Overflow See other posts from Stack Overflow or by Mike
Published on 2010-04-27T13:09:02Z Indexed on 2010/04/30 11:57 UTC
Read the original article Hit count: 297

At first I was using this as an extension method to update my detached entities...

Public Sub AttachUpdated(ByVal obj As ObjectContext, ByVal objectDetached As EntityObject)
    If objectDetached.EntityState = EntityState.Detached Then
        Dim original As Object = Nothing
        If obj.TryGetObjectByKey(objectDetached.EntityKey, original) Then
            obj.ApplyCurrentValues(objectDetached.EntityKey.EntitySetName, objectDetached)
        Else
            Throw New ObjectNotFoundException()
        End If
    End If
End Sub

Everything has been working great until I had to update non-scalar properties. Correct me if I am wrong but that is because "ApplyCurrentValues" only supports scalars. To get around this I was just saving the FK_ID field instead of the entity object relation. Now I am faced with a many to many relationship so its not that simple. I would like to do something like this...

Dim Resource = RelatedResource.GetByID(item.Value)
Condition.RelatedResources.Add(Resource)

But when I call SaveChanges the added Resources aren't saved. I started to play around with self-tracking entities (not sure if they will help solve my prob) but it seems they cannot be serialized to ViewState and this is a requirement for me.

I guess one solution would be to add the xRef table as an entity and add the fks myself but I would rather it just work how I expect it too.

I am open to any suggestions on how to either save my many to many relationships or serialize self-tracking entities (if self-trackingwould even solve my problem). Thanks!

© Stack Overflow or respective owner

Related posts about entity-framework

Related posts about .NET