Linq2SQL: refresh an entity instance, when changed on the database

One of the scenario that become when we work with ORMs, is the data reliability. There are any cases in which the data we are consuming, are prior changed from another user or application, and we need to sync this data before to use it.

Supposing we are using Linq2SQL, we could resolve this issue, simply executing a refresh on the instance (or the instances) that we are working on, to reload any or all the values from the database onto our instance.

The following is an example:

// myDataContext is a Linq2SQL Data Context

myDataContext ctx = new


myEntityType instance = ctx.myEntityTypeSet.Where(set => set.ID == 1).Single();


// this is the refresh statement

ctx.Refresh(RefreshMode.KeepChanges, instance);


Values that can be assigned to RefreshMode enumeration are the following:

We can define the this parameter, in order to preserve the local changed values, or reload all values from database, overwriting local changes.

Linq2SQL: refresh an entity instance, when changed on the database

Understand if a property is nullable with C# and reflection

The framework .NET offers a series of classes in its System.Reflection namespace, that allows us to investigate inside a type, and understand a wide range of characteristics on the same type.

We can start from an istance to get its ancestor type and related specifics.

In this case, we would like to know if a property is nullable or not. A nullable type is a type that can be declared or assigned to null value.

But what is exactly a nullable type ?. Someone of you maybe haven’t heard it anymore. Follow this link and learn more about it.

For the scope of this post, we want to understand how to detect if a type is nullable.

Well, considering we have a class as the following:

public class MyClass


public int iNotNullable { get; set; }

public int? iNullable { get; set; }



we will be able to understand, starting from an instance of this class, what are the nullable properties present in related type, in this manner:

MyClass c = new MyClass ();

Type T = c.GetType();

PropertyInfo[] properties = T.GetProperties();

foreach (PropertyInfo pi in properties)


// this is the statement to detect if the property is nullable

bool bNullable = pi.PropertyType.IsGenericType &&

pi.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>);


Console.WriteLine(“{0} is {1}nullable”, pi.Name, bNullable ? string.Empty : “not “);



That’s all.

Understand if a property is nullable with C# and reflection