Skip to content

Instantly share code, notes, and snippets.

@QuantumHive
Created June 21, 2017 10:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save QuantumHive/e80598ee8a84badd23c3ce7cb437088e to your computer and use it in GitHub Desktop.
Save QuantumHive/e80598ee8a84badd23c3ce7cb437088e to your computer and use it in GitHub Desktop.
Entity Framework 6: Clone object except ID
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
namespace ConsoleApplication1
{
public class MyDbContext : DbContext
{
public MyDbContext()
: base("name=MyDbContext")
{
Database.SetInitializer(new DropCreateDatabaseAlways<MyDbContext>());
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<MyEntity>()
.HasKey(m => m.Id)
.Property(m => m.Id)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
}
public virtual DbSet<MyEntity> MyEntities { get; set; }
}
public class MyEntity
{
public int Id { get; set; }
public string Name { get; set; }
public string CopyField { get; set; }
}
}
namespace ConsoleApplication1
{
internal class Program
{
private static void Main()
{
using (var db = new MyDbContext())
{
db.MyEntities.Add(new MyEntity
{
Name = "Hello",
CopyField = "CopyMe"
});
db.SaveChanges();
}
using (var db = new MyDbContext())
{
var model = db.MyEntities.Find(1);
model.Name = "Hello World";
db.MyEntities.Add(model);
db.SaveChanges();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment