7

オブジェクトをシリアル化された XML として返す Web メソッドがいくつかあります。オブジェクトの NHibernate マップされたプロパティをシリアル化するだけです...誰か洞察がありますか? 私のクラスではなく、Webメソッドが実際にNHibernateプロキシをシリアライズしているようです。[XMLInclude] と [XMLElement] を使用してみましたが、プロパティがまだシリアル化されていません。私はこれを回避するための本当に恐ろしいハック的な方法を持っていますが、もっと良い方法があるかどうか疑問に思いました!

このようなもの:

<?xml version="1.0" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" namespace="StoryManager" assembly="StoryManager">
  <class name="Graphic" table="graphics" lazy="false">
    <id name="Id" column="id" type="int" unsaved-value="0" >
      <generator class="identity"/>
    </id>

    <property name="Assigned" />
    <property name="Due" />
    <property name="Completed" />
    <property name="UglyHack" insert="false" update="false" />


    <many-to-one name="Parent" class="Story" column="story_id"/>

  </class>
</hibernate-mapping>

public class Graphic
{
    private int m_id;
    public virtual int Id
    {
        get { return m_id; }
        set { m_id = value; }
    }

    private DateTime? m_assigned;
    public virtual DateTime? Assigned
    {
        get { return m_assigned; }
        set { m_assigned = value; }
    }

    private DateTime? m_due;
    public virtual DateTime? Due
    {
        get { return m_due; }
        set { m_due = value; }
    }

    private DateTime? m_completed;
    public virtual DateTime? Completed
    {
        get { return m_completed; }
        set { m_completed = value; }
    }

    public bool UglyHack
    {
        get { return m_due < m_completed; } // return something besides a real mapped variable
        set {} // trick NHibernate into thinking it's doing something
    }
}

これは明らかにコードを書く方法ではありません。そこに「偽の」マッピング (UglyHack プロパティ) がない場合、そのプロパティはシリアル化されません。今のところ、(データ)転送オブジェクトの使用を検討しており、リフレクションを使用して何かに取り組んでいる可能性があります...

4

3 に答える 3

21

NH マップされたオブジェクトをシリアライズする最善の方法は、シリアライズしないことです :)。

ネットワーク経由で送信する場合は、実際に DTO を作成する必要があります。そのオブジェクトを作成したくない場合は、シリアル化したくないプロパティに [XmlIgnore] を設定できます。

すべてのプロパティが必要な場合は、それらをすべてデータベースからロードする必要があります - 一部の場合は熱心なロードで十分な場合があります (あまりにも多くの結合がデータの複製を開始する場合)。任意の方法でそのプロパティにアクセスする必要があります。負荷をトリガーします。

編集:

もう 1 つ付け加えておきたいことがあります。ドメイン エンティティをネットワーク経由で送信することは、常に悪い考えです。私の場合、私はそれを難し​​い方法で学びました-私はWebServiceを介していくつかのエンティティを公開します-そして今、私のドメインへのほとんどすべての変更(プロパティの名前変更、プロパティの削除など)は、WSを使用してアプリを強制終了します-さらに、たくさんのプロパティには [XmlIgnore] があります (循環依存関係を忘れないでください)。

すぐに書き直しを行いますが、これは二度とやりませんのでご安心ください。:)

編集 2

AutoMapperを使用して、エンティティから DTO にデータを転送できます。彼らはサイトにいくつかの例を持っています。

于 2009-07-28T03:58:50.447 に答える
4

WCF サービスの場合は、IDataContractSurrogate を使用できます

 public class HibernateDataContractSurrogate : IDataContractSurrogate
{
    public HibernateDataContractSurrogate()
    {
    }

    public Type GetDataContractType(Type type)
    {
        // Serialize proxies as the base type
        if (typeof(INHibernateProxy).IsAssignableFrom(type))
        {
            type = type.GetType().BaseType;
        }

        // Serialize persistent collections as the collection interface type
        if (typeof(IPersistentCollection).IsAssignableFrom(type))
        {
            foreach (Type collInterface in type.GetInterfaces())
            {
                if (collInterface.IsGenericType)
                {
                    type = collInterface;
                    break;
                }
                else if (!collInterface.Equals(typeof(IPersistentCollection)))
                {
                    type = collInterface;
                }
            }
        }

        return type;
    }

    public object GetObjectToSerialize(object obj, Type targetType)
    {
        // Serialize proxies as the base type
        if (obj is INHibernateProxy)
        {
            // Getting the implementation of the proxy forces an initialization of the proxied object (if not yet initialized)
            try
            {
                var newobject = ((INHibernateProxy)obj).HibernateLazyInitializer.GetImplementation();
                obj = newobject;
            }
            catch (Exception)
            {
               // Type test = NHibernateProxyHelper.GetClassWithoutInitializingProxy(obj);
                obj = null;
            }
        }

        // Serialize persistent collections as the collection interface type
        if (obj is IPersistentCollection)
        {
            IPersistentCollection persistentCollection = (IPersistentCollection)obj;
            persistentCollection.ForceInitialization();
            //obj = persistentCollection.Entries(); // This returns the "wrapped" collection
            obj = persistentCollection.Entries(null); // This returns the "wrapped" collection
        }

        return obj;
    }



    public object GetDeserializedObject(object obj, Type targetType)
    {
        return obj;
    }

    public object GetCustomDataToExport(MemberInfo memberInfo, Type dataContractType)
    {
        return null;
    }

    public object GetCustomDataToExport(Type clrType, Type dataContractType)
    {
        return null;
    }

    public void GetKnownCustomDataTypes(Collection<Type> customDataTypes)
    {
    }

    public Type GetReferencedTypeOnImport(string typeName, string typeNamespace, object customData)
    {
        return null;
    }

    public CodeTypeDeclaration ProcessImportedType(CodeTypeDeclaration typeDeclaration, CodeCompileUnit compileUnit)
    {
        return typeDeclaration;
    }
}

ホストでの実装:

foreach (ServiceEndpoint ep in host.Description.Endpoints)
        {
            foreach (OperationDescription op in ep.Contract.Operations)
            {
                var dataContractBehavior = op.Behaviors.Find<DataContractSerializerOperationBehavior>();
                if (dataContractBehavior != null)
                {
                    dataContractBehavior.DataContractSurrogate = new HibernateDataContractSurrogate();
                }
                else
                {
                    dataContractBehavior = new DataContractSerializerOperationBehavior(op);
                    dataContractBehavior.DataContractSurrogate = new HibernateDataContractSurrogate();
                    op.Behaviors.Add(dataContractBehavior);
                }
            }
        }
于 2011-05-04T11:40:39.790 に答える
0

sirrocco に同意します。私は、WCF を介して NHibernate エンティティをシリアル化しようとして最もひどい時間を過ごしました。最終的には、リフレクションを介して一般的に行われる DTO ソリューションを使用しました。

編集:ソリューション全体は大きすぎてここに投稿できず、もちろん私のニーズに合わせてカスタマイズされているため、関連するセクションをいくつか投稿します。

[DataContract]
public class DataTransferObject
{
    private Dictionary<string, object> propertyValues = new Dictionary<string, object>();
    private Dictionary<string, object> fieldValues = new Dictionary<string, object>();
    private Dictionary<string, object> relatedEntitiesValues = new Dictionary<string, object>();
    private Dictionary<string, object> primaryKey = new Dictionary<string, object>();
    private Dictionary<string,List<DataTransferObject>> subEntities = new Dictionary<string, List<DataTransferObject>>();

...

    public static DataTransferObject ConvertEntityToDTO(object entity,Type transferType)
    {
        DataTransferObject dto = new DataTransferObject();
        string[] typePieces = transferType.AssemblyQualifiedName.Split(',');

        dto.AssemblyName = typePieces[1];
        dto.TransferType = typePieces[0];

        CollectPrimaryKeyOnDTO(dto, entity);
        CollectPropertiesOnDTO(dto, entity);
        CollectFieldsOnDTO(dto, entity);
        CollectSubEntitiesOnDTO(dto, entity);
        CollectRelatedEntitiesOnDTO(dto, entity);

        return dto;
    }
....

     private static void CollectPropertiesOnDTO(DataTransferObject dto, object entity)
    {
        List<PropertyInfo> transferProperties = ReflectionHelper.GetProperties(entity,typeof(PropertyAttribute));

        CollectPropertiesBasedOnFields(entity, transferProperties);

        foreach (PropertyInfo property in transferProperties)
        {
            object propertyValue = ReflectionHelper.GetPropertyValue(entity, property.Name);

            dto.PropertyValues.Add(property.Name, propertyValue);
        }
    }

次に、DTO を復活させたい場合:

    private static DTOConversionResults ConvertDTOToEntity(DataTransferObject transferObject,object parent)
    {
        DTOConversionResults conversionResults = new DTOConversionResults();

        object baseEntity = null;
        ObjectHandle entity = Activator.CreateInstance(transferObject.AssemblyName,
                                                       transferObject.TransferType);

        if (entity != null)
        {
            baseEntity = entity.Unwrap();

            conversionResults.Add(UpdatePrimaryKeyValue(transferObject, baseEntity));
            conversionResults.Add(UpdateFieldValues(transferObject, baseEntity));
            conversionResults.Add(UpdatePropertyValues(transferObject, baseEntity));
            conversionResults.Add(UpdateSubEntitiesValues(transferObject, baseEntity));
            conversionResults.Add(UpdateRelatedEntitiesValues(transferObject, baseEntity,parent));
....

    private static DTOConversionResult UpdatePropertyValues(DataTransferObject transferObject, object entity)
    {            
        DTOConversionResult conversionResult = new DTOConversionResult();

        foreach (KeyValuePair<string, object> values in transferObject.PropertyValues)
        {
            try
            {
                ReflectionHelper.SetPropertyValue(entity, values.Key, values.Value);
            }
            catch (Exception ex)
            {
                string failureReason = "Failed to set property " + values.Key + " value " + values.Value;

                conversionResult.Failed = true;
                conversionResult.FailureReason = failureReason;

                Logger.LogError(failureReason);
                Logger.LogError(ExceptionLogger.BuildExceptionLog(ex));
            }
        }

        return conversionResult;
    }
于 2009-07-29T16:02:44.530 に答える