问题描述:

I found the following code here: Breeze BeforeSaveEntityonly only allows update to Added entities in the second answer. As fas as I understand it cannot work (as-is) because the property ModificationDate is not a known property of a generic Entity. I got a compile error object does not contain a definition for 'ModificationDate' and no extension method 'ModificationDate' accepting a first argument of type 'object' could be found

protected override bool BeforeSaveEntity(EntityInfo entityInfo)

{

if(entityInfo.EntityState== EntityState.Modified)

{

var entity = entityInfo.Entity;

entityInfo.OriginalValuesMap.Add("ModificationDate", entity.ModificationDate);

entity.ModificationDate = DateTime.Now;

}

}

We should proceed like this:

protected override bool BeforeSaveEntity(EntityInfo entityInfo)

{

if(entityInfo.EntityState== EntityState.Modified)

{

Product entity = (Product)entityInfo.Entity;

entityInfo.OriginalValuesMap.Add("ModificationDate", entity.ModificationDate);

entity.ModificationDate = DateTime.Now;

}

}

Then with this modified version of the code, the entity named Product has a property named ModificationDate and then everything compiled well.

My question: what if we still want to use a generic entity (using the var declaration) because we would like to use this code for different entity (Product, Clients, ...). Is it possible?

Hope my question is clear enough.

Thanks.

网友答案:

You can use the c# 'dynamic' keyword. This code should work as long as the entity (of whatever type) has a "ModificationDate" property.

protected override bool BeforeSaveEntity(EntityInfo entityInfo)  
{
  if(entityInfo.EntityState== EntityState.Modified)
  {
     var entity = (dynamic)entityInfo.Entity;
     entityInfo.OriginalValuesMap.Add("ModificationDate", entity.ModificationDate);
     entity.ModificationDate = DateTime.Now;
  }
}
相关阅读:
Top