开发者

Get list of properties of an entity

开发者 https://www.devze.com 2023-04-07 20:09 出处:网络
I\'m using entity framework. I would like to get the property list of an entity when the EntityState of the object is \"Added\", and loop throught them.

I'm using entity framework.

I would like to get the property list of an entity when the EntityState of the object is "Added", and loop throught them.

here is a sample code of what I'm doing.

var newEntities = ObjectStateManager.GetObjectStateEntries(EntityState.Added);
foreach (var entry in newEntities)
{
    var entityName = entry.EntitySet.Name;
    var newProps = ObjectStateManager.GetObjectStateEntry(entry.EntityKey).GetModifiedProperties();
    var currentNewValues = ObjectStateManager.GetObjectStateEntry(entry.EntityKey).CurrentValues;

    foreach (var propName in newProps)
    {
        var newValue = currentNewValues[propName];
    }
}

As you can see, I use

ObjectStateManager.GetObjectStateEntry(entry.EntityKey).GetModifiedProperties();

to get the property list, but It's working only when the State is EntityState.Modified.

Thanks.

Here is the way to perform my needs

With that, I can get all the attribute for an entity and get his value too.

 var newEntities = ObjectStateManager.GetObjectStateEntries(EntityState.Added);
 foreach (var entry in newEntities)
 {
      if (entry.State == EntityState.Added)
      {
           var prop = entry.Entity.GetType().GetProperties();
           var entityName = entry.EntitySet.Name;

           var currentNewValues = ObjectStateManager.GetObjectStateEntry(entry.EntityKey).CurrentValues开发者_如何学C;
           foreach (var propName in prop.Where(p => p.PropertyType.Namespace == "System"))
           {
                var newValue = currentNewValues[propName.Name];
           }
      }
 }


foreach (var entry in newEntities)
{
    if (entry.State == EntityState.Added)
    {
        // continue and get property list
        var currentValues = entry.CurrentValues;
        for (var i = 0; i < currentValues.FieldCount; i++)
        {
            var fName = currentValues.DataRecordInfo.FieldMetadata[i].FieldType.Name;
            var fCurrVal = currentValues[i];
        }
    }
}


Each entry you are enumerating over should have a 'State' property which is the EntityState, so you can either filter them out with an if clause or use linq,

        foreach (var entry in newEntities)
        {
            if (entry.State == EntityState.Added)
            {
                  // continue and get property list
            }
        }

Or

        var addedEntities = newEntities.Where(x => x.State == EntityState.Added); 

Also I'm not sure if you need to look at 'Modified Properties' at all. If it is an entity which has only just been added then why would it have any modified properties and not simply new ones (ie CurrentValues)?

0

精彩评论

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