Data Access has been discontinued. Please refer to this page for more information.

How to: Handle Database Default Values

This article is relevant to entity models that utilize the deprecated Visual Studio integration of Telerik Data Access. The current documentation of the Data Access framework is available here.

This topic demonstrates how to work with default values.

In the current version of Telerik Data Access default values are supported only for Database First Scenario. In Model First Scenario Telerik Data Access will not generate any SQL that will create default constraints.

You can specify a default value that will be entered in the column on the server. It could be either hard coded value or a function. For example: the default value for the nullable Rating column from the Cars table is 10.

When you create a new domain model, Telerik Data Access will automatically detect that a server side mechanism for setting default value will be used. The corresponding MetaColumn item will be generated with HasDefaultValue set to True.

You need make sure that the Nullable property for the corresponding CLR property in the Visual Designer is set to True, even if the underlying db column is not nullable. The point here is that if the CLR property is not nullable (Nullable = false) and you create a new instance of the class, then the property will be initialized with the CLR default value. If you create a new instance of Car, the Rating property will be 0.0 and that will be the value inserted in the database.

How to Set Null Values For Nullable Columns That Has a Server Side Mechanism for Default Values

During runtime if you try to insert a new object with null for the property corresponding to the default value column, the column will be omitted from the generated insert statement. Thus the default value generated from the server will be respected. If you set something different than null, the default value of the column will not be respected and the explicit value will be inserted.

To set null values, you need to reset the HasDefaultValue property of the column to False:

  1. In the Visual Designer, open the Model Schema Explorer.
  2. Locate the target column and press F4 to open the Properties pane.
  3. Set the HasDefaultValue to False.

Now, you will be able to assign a null value to the corresponding property. After this modification in the domain model, the server side default value will not be respected on insert.

However, it is still possible to initialize your new persistent objects with default values. As a further improvement, you could create a new partial class and set the default value for the property in the constructor.

public partial class Car
{
   public Car()
   {
       this.Rating = 10; // Server default value.
   }
}
Partial Public Class Car
 Public Sub New()
  Me.Rating = 10 ' Server default value.
 End Sub
End Class