Detect if a Entity is new
-
Monday, January 17, 2011 7:39 PMHi there, I'm trying to detect in a generic way if a entity is a new. I want to avoid a database roun trip. So i would check if the id property is null or zero. But is there any possibility to detect the id property (also in a generic way)? I didn't found any metadata which contains any information about the entity.
Mattia Baldinger http://www.mbaldinger.com/
All Replies
-
Tuesday, January 18, 2011 12:26 AM
Not sure with DbContext this can be made simpler but u can do something like this
public bool ExistsInDatabase<T>(T obj) where T:class
{
bool exists = false;
var ctx = ((IObjectContextAdapter)this).ObjectContext;
var entry = this.Entry(obj);
if (entry.State != EntityState.Detached)
{
var set = Context.CreateObjectSet<T>().EntitySet;
var keyprop = set.ElementType.KeyMembers.First();
//if the key is integer we can check based on if id > 0 or not
if (keyprop.TypeUsage.EdmType.Name == "Int32")
{
int keyval = entry.CurrentValues.GetValue<int>(keyprop.Name);
if (keyval > 0)
{
exists = true;
}
}
else
{
var databasevalues = entry.GetDatabaseValues();
if (databasevalues != null)
{
exists = true;
}
}
}
return exists;
}var db = new NorthWindEntities();
var cat = db.Categories.AsNoTracking().First();
db.Entry<Category>(cat).State = System.Data.EntityState.Added;
var isnew = db.ExistsInDatabase<Category>(cat);
Console.WriteLine(isnew);
Zeeshan Hirani Entity Framework 4.0 Recipes by Apress
http://weblogs.asp.net/zeeshanhirani- Proposed As Answer by Arthur Vickers - MSFTModerator Wednesday, January 19, 2011 5:25 PM
-
Friday, December 23, 2011 3:28 PM
I've created a blog post about this. Basically I check the EntityKey of the object to determine if the object is new:return entity.EntityKey == null || entity.EntityKey.IsTemporary;

