更新时间:2023-02-11 20:22:31
从EF Core 2.0开始,可以使用 IProperty.AfterSaveBehavior
属性:
Starting with EF Core 2.0, you can use IProperty.AfterSaveBehavior
property:
获取一个值,该值指示在将实体保存到数据库之后是否可以修改此属性。
Gets a value indicating whether or not this property can be modified after the entity is saved to the database.
如果抛出,然后在数据库中存在该实体后,如果为此属性分配新值,将引发异常。
If Throw, then an exception will be thrown if a new value is assigned to this property after the entity exists in the database.
如果忽略,那么将忽略对数据库中已经存在的实体的属性值的任何修改。
If Ignore, then any modification to the property value of an entity that already exists in the database will be ignored.
您需要的是忽略
选项。在撰写本文时,还没有专用的流利API方法,但是在更新过程中设置显式值包含一个示例,您可以做到这一点。
What you need is the Ignore
option. At the time of writing there is no dedicated fluent API method for that, but Setting an explicit value during update contains an example how you can do that.
以您的示例为例:
modelBuilder.Entity<MyObject>(builder =>
{
builder.Property(e => e.Prop7).Metadata.AfterSaveBehavior = PropertySaveBehavior.Ignore;
builder.Property(e => e.Prop8).Metadata.AfterSaveBehavior = PropertySaveBehavior.Ignore;
builder.Property(e => e.Prop9).Metadata.AfterSaveBehavior = PropertySaveBehavior.Ignore;
});
现在都
public void UpdateObj(MyObject objToUpdate)
{
var myObj = _db.MyObject.First(x => x.Id == objToUpdate.Id);
_db.Entry(myObj).CurrentValues.SetValues(myObjToUpdate);
_db.SaveChanges();
}
和
public void UpdateObj(MyObject objToUpdate)
{
_db.Update(myObjToUpdate);
_db.SaveChanges();
}
将忽略 Prop7
, Prop8
和 Prop9
值传递的 myObjToUpdate
。
will ignore Prop7
, Prop8
and Prop9
values of the passed myObjToUpdate
.
更新(EF Core 3.0 +)上述属性已由 GetAfterSaveBehavior 和 SetAfterSaveBehavior 扩展方法。
Update (EF Core 3.0+) The aforementioned property has been replaced with GetAfterSaveBehavior and SetAfterSaveBehavior extension methods.