Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
604 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 Reply

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; }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...