英文:
Entity Framework : entityTypeConfiguration set prop value only on update
问题
I would expect that when using ValueGeneratedOnUpdate
, the specific value generator would only be called if the entity has been updated (so the entity already exists).
Instead it seems that the value is generated on add as well.
This is how I'm configuring the create and update props:
builder.Property(self => self.CreatedAt)
.ValueGeneratedOnAdd()
.HasValueGenerator<UtcTimeValueGenerator>();
builder.Property(self => self.UpdatedAt)
.ValueGeneratedOnUpdate()
.HasDefaultValue(null)
.HasValueGenerator<UtcTimeValueGenerator>();
Seed data:
builder.HasData(new List<Device>
{
new Device
{
Id = 1,
ParkingLotId = 1,
Serial = "test",
SigfoxSerial = "test"
}
});
Generator:
public class UtcTimeValueGenerator : ValueGenerator<DateTime>
{
public override bool GeneratesTemporaryValues => false;
public override DateTime Next(EntityEntry entry)
=> DateTime.UtcNow;
}
Using IEntityTypeConfiguration<T>
only, can a datetime property be set for a specific column only if the entry already exists.
英文:
I would expect that when using ValueGeneratedOnUpdate
the specific value generator would only be called if the entity has been updated (so the entity already exists).
Instead it seems that the value is generated on add as well.
This is how I'm configuring the create and update props
builder.Property(self => self.CreatedAt)
.ValueGeneratedOnAdd()
.HasValueGenerator<UtcTimeValueGenerator>();
builder.Property(self => self.UpdatedAt)
.ValueGeneratedOnUpdate()
.HasDefaultValue(null)
.HasValueGenerator<UtcTimeValueGenerator>();
Seed data.
builder.HasData(new List<Device>
{
new Device
{
Id = 1,
ParkingLotId = 1,
Serial = "test",
SigfoxSerial = "test"
}
});
Generator
public class UtcTimeValueGenerator : ValueGenerator<DateTime>
{
public override bool GeneratesTemporaryValues => false;
public override DateTime Next(EntityEntry entry)
=> DateTime.UtcNow;
}
Using IEntityTypeConfiguration<T> only, can a datetime propery be set for a specific column only if the entry already exist.
答案1
得分: 0
相反,您可以使用 Nullable<DateTime>
生成器。在 Next
函数中,您可以检查状态并决定是否生成新值。
public class UtcTimeValueGenerator : ValueGenerator<DateTime?>
{
public override bool GeneratesTemporaryValues => false;
public override DateTime? Next(EntityEntry entry)
=> entry.State == EntityState.Modified ? DateTime.UtcNow : null;
}
英文:
Instead, you can use a Nullable<DateTime>
generator. And in the Next
function you can check the state and decide whether to generate a new value or not.
public class UtcTimeValueGenerator : ValueGenerator<DateTime?>
{
public override bool GeneratesTemporaryValues => false;
public override DateTime Next(EntityEntry entry)
=> entry.State == EntityState.Modified ? DateTime.UtcNow : null;
}
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论