The LINQ to SQL entites don’t have a property that lets you know if the instance of the object has been loaded from the database or has been locally created, i.e. new.
A simple solution to this problem is to add an enumeration with the enums New and Loaded:
public enum EntityState
{
[Description("New")]
New = 0,
[Description("Loaded")]
Loaded = 1
}
Then create a property in the partial class of your LINQ to SQL entity for the enumeration:
public EntityState EntityState
{
get { return _EntityState; }
private set { _EntityState = value; }
}
Then in the partial method OnCreated set the property’s value to New and in the partial method OnLoaded set it to Loaded:
partial void OnCreated()
{
EntityState = EntityState.New;
}
partial void OnLoaded()
{
EntityState = EntityState.Loaded;
}
Now if you create a new entity only the OnCreated method will be executed, and if its loaded from the db the OnCreated will be fired and then the OnLoaded. So you can now easily determine its state.
Of course you could also check the primary key’s value against the default for its type but that is not ideal, the primary key is not nullable so for an integer primary key you would have to check if it is 0 to determine if its new or not. Rather avoid that approach.
Disclaimer: This post is based on Orcas CTP June 2007