Created
June 21, 2017 10:21
-
-
Save QuantumHive/e80598ee8a84badd23c3ce7cb437088e to your computer and use it in GitHub Desktop.
Entity Framework 6: Clone object except ID
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; } | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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