I am using Entity Framework 5 (DBContext
) and I am trying to find the best way to deep copy an entity (i.e. copy the entity and all related objects) and then save the new entities in the database. How can I do this? I have looked into using extension methods such as CloneHelper
but I am not sure if it applies to DBContext
.
相关问题
- Using StoreGeneratedPattern.Identity with database
- Giving database context to object Factory
- PagedList package installed, “missing assembly ref
- How to use DBContext.Add/Attach (using EF CodeFirs
- How does Entity Framework decide whether to refere
相关文章
- How Can I Use Custom Validation Attributes on Chil
- what is the best practice to set up DbContext in S
- Ignore Properties in OnModelCreating
- MVC. Net Error: Format of the initialization strin
- Two One-to-Many relationships in the same table
- Should we use Data Repository pattern in MVC appli
- Mocking DBSet, EF Model First
- DbContext ChangeTracker: Id of Added Entity for Au
This is a generic extension method which allows generic cloning.
You have to fetch
System.Linq.Dynamic
from nuget.The only thing you have to implement yourself is the GetKeyName method. This could be anything from
return typeof(TEntity).Name + "Id"
toreturn the first guid property
or return the first property marked withDatabaseGenerated(DatabaseGeneratedOption.Identity)]
.In my case I already marked my classes with
[DataServiceKeyAttribute("EntityId")]
Here's another option.
I prefer it in some cases because it does not require you to run a query specifically to get data to be cloned. You can use this method to create clones of entities you've already obtained from the database.
This method copies the current values from the source to a new row that has been added.
One cheap easy way of cloning an entity is to do something like this:
the trick here is AsNoTracking() - when you load an entity like this, your context do not know about it and when you call SaveChanges, it will treat it like a new entity.
If
MySet
has a reference toMyProperty
and you want a copy of it too, just use anInclude
: