Differences between Attach and EntityState. Modified modes in Entity Framework update mode,
The database has a City table.
Initial data:
Ing between object classes and Fluent APIs
public class City { public int Id { get; set; } public string Name { get; set; } public int? ParentId { get; set; } }
View Code
public class CityMap : EntityTypeConfiguration<City> { public CityMap() { ToTable("City"); HasKey(c => c.Id); Property(c => c.Name).HasMaxLength(50); } }
View Code
Entity Framework context class
public class EFContext : DbContext{ public EFContext() : base("name=MyConnection") { } public DbSet<City> Citys { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { Database.SetInitializer<EFContext>(null); modelBuilder.Configurations.Add(new CityMap()); base.OnModelCreating(modelBuilder); }}
View Code
Method 1: Use Attach and update the value of an attribute (note that not all attributes are modified)
Using (var context = new EFContext () {// method 1 var entity = context. citys. find (4); context. citys. attach (entity); entity. name = "Zhaoqing"; context. saveChanges ();}
Changed Shenzhen to Zhaoqing. From SQL Profiler, we can see that the generated update statement only modifies the name column.
Using (var context = new EFContext () {// method 2 var model = context. citys. find (5); model. name = "Chaozhou"; context. entry (model ). state = System. data. entity. entityState. modified; context. saveChanges ();}
Change Zhuhai to Chaozhou. Note that the ParentId is not modified this time, but the statements generated in SQL Profiler show that the Update statement modifies all columns (except primary keys)
When an entity is marked as System. Data. Entity. EntityState. Modified, all columns are updated (not only when the column is Modified). Which method of field of view is used in this case.
Finally, the data in the database is:
References:
Https://stackoverflow.com/questions/30987806/dbset-attachentity-vs-dbcontext-entryentity-state-entitystate-modified
Https://msdn.microsoft.com/en-us/data/jj592676