The following is a person entity in EF Core:
Public Partial classperson{ Public intId {Get;Set; } Public stringCode {Get;Set; } Public stringName {Get;Set; } PublicDatetime? Createtime {Get;Set; } PublicDatetime? UpdateTime {Get;Set; }}
Where we specify by the fluent API that code is the key property, which is used to update and delete data:
Modelbuilder.entity<person> (Entity ={ = e.id). Valuegeneratedonadd (); = E.code); // The Declaration column code is the entity's key Property });
Now we can make a new person entity from the code, then declare the value of its key property column code, and the value of the column name to be modified so that EF core generates an SQL statement for us that only modifies the column name:
using(Testdbcontext Testdbcontext =NewTestdbcontext ()) { person person=NewPerson () {Code ="A", name="Tom"};//column code is key, declaring the value of the key property column code, and the value of the column name to be modifiedTestdbcontext.attach (person);//tell EF Core to start tracking changes to the person entityTestdbcontext.entry (person). Property (P = p.name). IsModified =true;//tells the EF core entity that the Name property of the person has changed and needs to update the column in the database when SaveChangestestdbcontext.savechanges ();}
This avoids the need to change the value of an entity through EF core, which must first be removed from the database and then updated back, resulting in inefficiency. We can see the SQL statements generated in the background by the EF core, which update only the value of the person table name column and not update the values of the other columns:
=============================== EF Core Log started ===============================executed DbCommand (23MS) [ parameters=[@p1 = '? ' (Size =), @p0 = '? ' (Size = +)], commandtype= ' Text ', commandtimeout= ']set NOCOUNT on; UPDATE [Person] SET [Name] = @p0WHERE [Code] = @p1; SELECT @ @ROWCOUNT; =============================== EF Core Log finished ===============================
How EF core only update part of the column data for an entity