Luuk Krijnen
Luuk Krijnen

Reputation: 1192

Is it possible to create a readonly property using Linq to SQL

I'm using a database with in some tables there are values stored by triggers. In this case a 'lastModifiedDate' and a 'createdDate' field. The 'lastModifiedDate' field is updated by a trigger. The 'createdDate' field is filled using a default value using a getdate() command.

now in my program i don't wanna think about the values of this fields. Only wanna read en display them. In all other cases the value may remain null. Only when Updating errors occur because Linq wants to update this fields while not date is set.

Is it possible to use linq while preventing linq to update the specified columns.

Upvotes: 1

Views: 1007

Answers (2)

Oleks
Oleks

Reputation: 32343

An answer from the Frequently Asked Questions (LINQ to SQL):

Avoiding Explicit Setting of Database-Generated Values on Insert or Update

Q. I have a database table with a DateCreated column that defaults to SQL Getdate(). When I try to insert a new record by using LINQ to SQL, the value gets set to NULL. I would expect it to be set to the database default.

A. LINQ to SQL handles this situation automatically for identity (auto-increment) and rowguidcol (database-generated GUID) and timestamp columns. In other cases, you should manually set IsDbGenerated=true and AutoSync=Always/OnInsert/OnUpdate properties.

In addition I suggest to eliminate the setter from the property by changing its IsReadOnly flag to true.

Upvotes: 1

KristoferA
KristoferA

Reputation: 12397

Set the IsDbGenerated attribute on the property to true...

Upvotes: 1

Related Questions