Question

The title pretty means what i'm trying to do. There is a way to know if an object instance is transient? (Or, at least, was not saved yet?)

Thank you all!

PS.: Not using Exists method.

Était-ce utile?

La solution

Usually this is done comparing the value of the entity's PK property with the defined unsaved-value. The most common case is having an int PK without a defined unsaved-value, e.g.:

[PrimaryKey]
public virtual int Id {get;set;}

In this case the unsaved-value is 0, so you can just compare the value of Id with 0 to find out if it's transient or not.

If you want to do this more generically, you can get the unsaved-value from the ActiveRecord model and compare against that using reflection, e.g. (untested!):

var entity = new MyEntity();
var pk = ActiveRecordModel.GetModel(typeof(MyEntity)).PrimaryKey;
var unsavedValue = pk.PrimaryKeyAtt.UnsavedValue;
var convertedUnsavedValue = Convert.ChangeType(unsavedValue, pk.Property.PropertyType);
var pkValue = pk.Property.GetValue(aform, null);
var transient = Equals(convertedUnsavedValue, pkValue);

This will probably fail in the face of null UnsavedValues (in that case you should compare with the default value of the PK type), but it should get you started.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top