Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You can check if an object has a public settable property with a certain name using this code:</p> <pre><code>public static bool HasWritableProperty(this object objectToCheck, string propertyName) { var type = objectToCheck.GetType(); //get a property info for the property, but only if it is a public instance property var pi = type.GetProperty(propertyName, BindingFlags.Instance | BindingFlags.Public) //return false if no propery is found if (pi==null) return false; //get the set method for the property var setter = pi.GetSetMethod(); //if it's null the property is not writable return (setter != null); } </code></pre> <p>However, this is not a very efficient code, as it uses a lot of reflection.</p> <p>If you go this route, I would memoize the result of this code, so every check will be run at most once.</p> <p>What I actually do in my projects (I use EF Code First), is have a <code>BaseEntity</code> class that has the properties that are common, and have the concrete entities inherit from the <code>BaseEntity</code> class. Then I have a <code>FillEntityMetadata</code> method, that is more or less this:</p> <pre><code>protected void FillEntityMetadata(BaseEntity entity, bool isUpdate = false) { // Set audit data. if (!isUpdate) { entity.CreatedBy = CurrentUser.ID; entity.CreatedOn = DateTime.Now; entity.IsActive = true; } entity.LastModifiedBy = CurrentUser.ID; entity.LastModifiedOn = DateTime.Now; } </code></pre> <p>Note that for this to work, you can also use an interface, <code>IBaseEntity</code>, and it would function in the same way.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload