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

跟風遠走 提交于 2019-12-11 20:09:58

问题


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



来源:https://stackoverflow.com/questions/19748112/unable-to-cast-object-of-type-system-data-objects-objectstateentrydbupdatabledat

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!