无法将类型为System.Data.Objects.ObjectStateEntryDbUpdatableDataRecord的对象转换为ComplexType [英] Unable to cast object of type System.Data.Objects.ObjectStateEntryDbUpdatableDataRecord to ComplexType

查看:247
本文介绍了无法将类型为System.Data.Objects.ObjectStateEntryDbUpdatableDataRecord的对象转换为ComplexType的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从ObjectStateEntry获取一个字符串值,并具有以下转换器。
我的客户类别具有一个复杂的地址字段。但是我的代码无法解决这个问题。

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
    }

错误消息是

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

域类为

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

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


推荐答案

CurrentValues 集合不包含您的域类型的实例。它具有独立于您的域模型的统一表示,因此您无法将其数据类型转换为您的类型。

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.

如果要获取地址,则需要从 entry.Entity 中提取地址或从中创建新实例从 CurrentValues

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

这篇关于无法将类型为System.Data.Objects.ObjectStateEntryDbUpdatableDataRecord的对象转换为ComplexType的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆