开发者

Check if entity is new in EF 4.0

I need to check if an entity is new. If it was an int/identity primary key, I could just check if the property for the key has a default value...but in the case of a Guid开发者_运维技巧, I can't do this. Is there anything I can do with the ObjectContext or ObjectStateManager to have it check and determine if the entity in question is new vs. modified?


ObjectStateManager.GetObjectStateEntry

using (MyContext context = new MyContext())
{
    ObjectStateManager objectStateManager = context.ObjectStateManager;
    EntityState state = objectStateManager.GetObjectStateEntry(obj).State;
}


In the case of a Guid you can do this

if(foo.GuidProperty == default(Guid))
{

}


If it's a nullable Guid, you can check if it has a value:

if (entity.MyGuid.HasValue)
{
  // hooray!
}

If it's not nullable, check for default value or an empty GUID:

if (entity.MyGuid != default(Guid))
{
  // hooray!
}

if (entity.MyGuid != Guid.Empty)
{
  // hooray!
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜