Unable to cast object of type System.Data.Objects.

2019-08-30 10:07发布

问题:

I want to get a string value from an ObjectStateEntry and have the following converter. My customer class has an address field which is a complex type. However my code fails to handle this.

   private static string EntryToString( ObjectStateEntry entry, string fieldName, Context Db)
    {
        try
        {
            string fieldValue = "";
            int ordinal = 0;
            var createdField = entry.CurrentValues.DataRecordInfo.FieldMetadata.FirstOrDefault(f => f.FieldType.Name == fieldName);
            var fieldType = createdField.FieldType.TypeUsage.EdmType.Name;
            ordinal = createdField.Ordinal;
            switch (fieldType)
            {
                case "String":   
                    fieldValue = entry.CurrentValues[ordinal].ToString();
                    break;
                case "Address"
                    var obj = entry.CurrentValues[ordinal];

                    var adr = (Address)obj; // error occurs here

                    fieldValue = Serialize(adr);  // converts to string

                    break;
               // other cases
           } 
          return fieldValue
    }

Error message is

  System.InvalidCastException: Unable to cast object of type 'System.Data.Objects.ObjectStateEntryDbUpdatableDataRecord' to type '.DomainClasses.Address'.

The domain classes are

public class Customer
{
    public Customer()
    {
        this.Address = new Address();
    }
    // other fields
 }

[ComplexType]
[Serializable]
public class Address
{
    public string AddressLine1 { get; set; }
    // other fields
}

回答1:

CurrentValues collection doesn't hold instances of your domain types. It has its own unified representation independent on your domain model so you cannot casts its data type to your types.

If you want to get an address you need to extract it from entry.Entity or create a new instance from information extracted from CurrentValues