Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
607 views
in Technique[技术] by (71.8m points)

.net - How to ignore a particular field from an Entity model upon insert?

We have a field in our SQL Server database table which is autogenerated by SQL Server, the field is called CreatedTime.

We have mapped the whole database table to our datamodel in Entity Framework, thus also the field CreatedTime.

When we insert a new row in the database, via Entity Framework, we thus do not provide any value for CreatedTime.

This causes the insert to fail with the error:

SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM

So the question is: Is there is a way to to exclude a particular field in the Entity datamodel in the Entity Framework insert statement? So that we will not get the above error?

We would like to keep the field CreatedTime in the Entity model, because we might want to access it later.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If using Fluent API:

using System.ComponentModel.DataAnnotations.Schema;

this.Property(t => t.CreatedTime)
            .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Computed);

If using Annotations

[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public System.DateTime CreatedTime { get; set; }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...