views:

205

answers:

2

Hello,

I'm new to the Entity Framework and am currently experimenting with it. I created a simple database, set up the model in VS2008, and have got the code going to query the database using the EF as well as inserting new data.

There's one thing that has me a little confused though. I have an entity (set up in my model) called Customer, and as part of the logic of my application I want to be able to create a temporary Customer object for some intermediate processing. This particular object should never actually be stored in the database. However, I noticed that as soon as I call SaveChanges() the customer is saved to the database. This isn't what I want to happen. I'd be quite happy to call AddCustomer() on the objects I do want to include - I just want to have the option to create a temporary instance for my own use.

I did discover I could call Detach() and pass in my temporary instance, which would stop it from being persisted. However I'm not sure this is the best way to do this since the temporary Customer object will have related objects, and unless I go through and detach them all I might end up in hot water.

It's possible I'm misunderstanding something about how the EF is supposed to work, or that I'm missing something obvious - I'm hoping someone can set me straight!

Thanks

John

A: 

If you want to have a temporary instance of an entity that'll never be connected to the EF again, use this Entity Cloner for cloning the entity

If you are trying to disconnect an entity, send it over the wire some where (let us say pass it over to the client over a service, to modify it, and then again get it back), and again merge back the changes to the EF - right now this is not directly supported. How ever, you can try these solutions

Entity Bag:

EFContrib (you need PostSharp4EF)

amazedsaint
Thanks very much for that. I'm actually creating entirely new objects rather than cloning them - ideally what I'd like to be able to do it goCustomer cust = new Customer();without that ever being put into the EF unless I specifically sayentities.AddToCustomer(cust);I'm not sure those links would allow me to do something like this?
John
A: 

Why not have another Customer class with the same fields?

Carles
That's a possibility - but then on the occasions when I do need to persist one of the temporary objects, I'd need to convert it to an EF object. Also, this gets pretty wild if I have child objects off Customer (e.g. Order) which I'm manipulating - now I'd have in-memory versions of Customer, Order, Address, etc, as well as the EF versions.It's certainly a way around the problem - but it seems like a lot of work, and a lot of unnecessary work given that EF already made up these classes for me!Thanks for the suggestion though.
John

related questions