Runtime Field Exist Check

Posts   
 
    
jshallard
User
Posts: 62
Joined: 23-Mar-2005
# Posted on: 12-Sep-2005 21:56:27   

I have been having a go at coming up with some generic runtime code that will let me take certain actions based upon the presence of certain fields. I have been using entity.Fields["FieldName"] to access fields. This allows me to come up with code such as this:


public static void UpdateAutoFields(IEntity entity)
{
…

    if(entity.Fields["LastModifiedBy"] != null)
    {
        entity.Fields["LastModifiedBy"].CurrentValue =System.Threading.Thread.CurrentPrincipal.Identity.Name;
    }

…
}

One of the problems i am running into with this, is that if a field does not exist, the code entity.Fields["FieldName"] throws an ArgumentException (originating in SD.LLBLGen.Pro.ORMSupportClasses.EntityFields). I can get round this by putting all such code in try/catch blocks, but this is very inefficient.

Does a method exist to check if a field exists in an entity? If not, what would be the chance of adding one to the EntityFields class? Something like the following:


public bool ContainsField(string name)
{
    return _entityFieldReferences.ContainsKey(name)
}

taylor74
User
Posts: 59
Joined: 06-Oct-2004
# Posted on: 12-Sep-2005 23:00:46   

Here's something you might try. This method wasn't designed for the purpose of detecting if a field exists in an entity, but it seems to work. The EntityBase.GetProperties method is actually part of the databinding support.

        ' Had to use EntityBase instead of IEntity interface.
        Dim myentity As EntityBase = New EntityClasses.LoadEntity
        Dim pdc As System.ComponentModel.PropertyDescriptorCollection = myentity.GetProperties(Nothing)
        ' Find returns null if property is not found.
        If pdc.Find("JobId", True) Is Nothing Then
            MessageBox.Show("Not found...")
        Else
            MessageBox.Show("Found...")
        End If

Wish I could find a more type safe way to do it, but for now, that's what I've come up with.

jshallard
User
Posts: 62
Joined: 23-Mar-2005
# Posted on: 13-Sep-2005 21:39:33   

It seems like a long way round - but that should do the trick for now!

Thanks for your help sunglasses