SOLVED: Don't you hate when you find the solution yourself a minute after posting? My self-answer is below.
Suppose I have a .NET Entity Framework model class:
public class Foo
{
public int FooId { get; set; }
public string Description { get; set; }
public DateTime Created { get; set; }
public DateTime LastUpdated { get; set; }
}
The Created and LastUpdated columns in my SQL Server table, both of type DATETIME2
, have a DEFAULT
constraint (SYSUTCDATETIME())
. An AFTER UPDATE
trigger sets LastUpdated to SYSUTCDATETIME
whenever the Description is changed.
In my code, when I'm reading from the Foo table, I want Created and LastUpdated included, because I want to use their values. But when I'm adding a row to the table, I don't want them included in the Add because I want SQL Server to use the default value I've configured it to use. I thought it would just have been a matter of having
Foo foo = new Foo
{
Description = "This is my latest foo."
}
but C# is giving the two date properties their own default value of 0001-01-01T00:00:00, which isn't null, and this is what's getting recorded in the table.
Isn't there an attribute that tells the framework not to write a property back to the database? It isn't NotMapped
because that would prevent the values from being read.
question from:
https://stackoverflow.com/questions/65909531/including-read-only-columns-in-an-entity-framework-model 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…