CompanyDroneFromSector7G
CompanyDroneFromSector7G

Reputation: 4517

Dynamics 2011 SDK Generic "Add new record" function

I'm trying to write a generic C# function to add a new record to a given entity. The trouble is that I can't tell what type each attribute is until I load an existing record, so I'm getting errors. I'm sure there's a way to do this.

The following code fragment shows what I have:

foreach (DataRow row in data.Rows) // <== gets data for new records from DataTable
{
    entity = new Entity(this.Entity); // <== an existing entity type
    Type columnType;
    foreach (SourceColumn column in this.Columns)
    {
        columnType = entity[column.Name].GetType(); // <== fails because not loaded
        entity[column.Name] = Convert.ChangeType(row[column.Name], columnType);
    }
    xrm.Create(entity);
}

What should I be doing instead?

Is there a way to load the entity definition without loading an entity record?

Thanks

Upvotes: 0

Views: 323

Answers (2)

James Wood
James Wood

Reputation: 17552

I think in this case you are best off using the metadata webservices.

If you use a RetrieveAttributeRequest as described here.

Then that will return you a RetrieveAttributeResponse with AttributeMetadata (MSDN), which has property for AttributeType.

Upvotes: 2

Marty
Marty

Reputation: 3555

You can You use reflection.

So Your code would look like this

var columnType = entity.GetType().GetProperties().First(p => p.Name == column.Name).GetType();

Upvotes: 0

Related Questions