Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 993
Rune Hansen Avatar asked May 02 '13 14:05

Rune Hansen


People also ask

How do I ignore a field in Entity Framework?

The Entity Framework Core Fluent API provides two Ignore methods. One belongs to the ModelBuilder class and is used to specify that the entity should not be mapped to a database table. The other Ignore method is available on the EntityTypeBuilder class and enables you to exclude individual properties from mapping.

What is SQL insert ignore?

INSERT IGNORE statement is used to skip the error messages while inserting rows into table. INSERT IGNORE Statement not supported in all databases. INSERT IGNORE statement works only in MySQL database.


2 Answers

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; }
like image 61
Jason Shehane Avatar answered Sep 19 '22 03:09

Jason Shehane


I found a simple solution to the problem on this thread:

http://social.msdn.microsoft.com/Forums/en-US/adodotnetentityframework/thread/7db14342-b259-4973-ac09-93e183ae48bb

There Fernando Soto writes:

"If you go to the EDM designer click on the field in the table that is auto-generated by the database, right click on it and select Properties and look at the properties windows click on StoreGeneratedPattern and set its value to Computed, I believe it will give you what you are looking for."

The above solution was super quick and easy and it seems to work.

Also thank you for your contributions guys, but the above solution seems to do the job.

like image 27
Rune Hansen Avatar answered Sep 19 '22 03:09

Rune Hansen