开发者

EF 4.0 Entity does not pick up new values after insert (select entity after insert)

I am using Entity Framework 4.0 POCO entity I have mapped custom stored procedure on insert PROCEDURE [dbo].[usp_MyTable_Insert] ( @Value1 char(1), @Value2 varchar(5), @Value3 varchar(20) .... ) AS BEGIN TRANSACTION INSERT INTO "dbo"."MyTable" ( "Value1", "Value2", "Value3" ) VALUES ( @Value1, @Value2, @Value3 )

DECLARE @Id int --Get the latest Id. SET @Id = ( SELECT CAST(@@IDENTITY AS INT) )

--update the table with the some values UPDATE "dbo"."MyTable" SET Value3 = ( SELECT SomeTableColumn FROM SomeTable WHERE Something = Something ) WHERE [Id] = @Id

COMMIT TRANSACTION

SELECT @Id AS "Id"

END

It is inserting entity into database and then updating some of the columns in database then returning identity. All pretty simple.

public int InsertRecord(RecEntity recEntity) { context.AddObject("RecEntities", recEntity);

        conte开发者_JAVA百科xt.SaveChanges();

        return recEntity.Id;
    } 

Method insert working well. Then i need to update current entity with values which stored procedure inserted. I have method in my repository to retrieve data

public RecEntity SingleRecEntity(Expression> where) { return context.RecEntities.Single(where); } When i am calling this method values values inserted by stored procedure doesn't come to entity.

id = repository.InsertRecord(recEntity); recEntity = repository.SingleBrokerPreRegistration(x => x.Id == id); // new values didnt come here from database

I run the query generated by entity framework in query analyzer, it is returning all up to date values. But fore some reason datacontext don't want to update this entity.

Probably there is should be some ways to change this. May be some one may explain this behaviour. Need help.


Try the Refresh method with the StoreWins parameter.
EF does not refresh the values in case there is already an attached object with Entity Key specified unless the Refresh method is not called explicitly


If you run .Load(Objects.MergeOption.OverwriteChanges) on the collection you'll get any newly added items. If you want the deleted items to be "refreshed" you'll need to detach the entities from the collection before running .Load

Putting it all together (sorry about the vb)

For Each child in Parent.ChildCollection.ToArray()
    context.Detatch(child)
Next
Parent.ChildCollection.Load(Objects.MergeOption.OverwriteChanges)

This works for me, but if there's a more elegant way I'd love to see it!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜