Сериализация свойств

Я искал везде в документах CF, часто задаваемых вопросах, блогах и записях SO, но до сих пор не могу понять, почему эта модель:

    <cf:project defaultNamespace="Humanisme" xmlns:cf="http://www.softfluent.com/codefluent/2005/1" xmlns:cfx="http://www.softfluent.com/codefluent/modeler/2008/1" xmlns:cfom="http://www.softfluent.com/codefluent/producers.model/2005/1" xmlns:cfps="http://www.softfluent.com/codefluent/producers.sqlserver/2005/1" xmlns:cfsm="http://www.softfluent.com/codefluent/producers.servicemodel/2007/1" defaultKeyPropertyTypeName="int" defaultMaxLength="240" persistencePropertyNameFormat="{1}" createDefaultMethodForms="true" createDefaultApplication="false" createDefaultHints="false">
  <cf:import path="Default.Surface.cfp" />
  <cf:producer name="Business Object Model (BOM)" typeName="CodeFluent.Producers.CodeDom.CodeDomProducer, CodeFluent.Producers.CodeDom">
    <cf:configuration compileWithVisualStudio="true" compile="false" codeDomProviderTypeName="CSharp" targetDirectory="..\Humanisme.classes" produceWebMembershipProvider="false" produceWebProfileProvider="false" produceWebBasicAuthenticationModule="false" cfx:targetProject="..\Humanisme.classes\Humanisme.classes.csproj" cfx:targetProjectLayout="Update">
      <subProducer typeName="CodeFluent.Producers.ServiceModel.ServiceProducer, CodeFluent.Producers.ServiceModel, Version=1.0.0.0, Culture=neutral, PublicKeyToken=1bb6d7cccf1045ec" compileWithVisualStudio="true" compile="false" codeDomProviderTypeName="CSharp" targetDirectory="..\Humanisme.webApi" silverlightTargetVersion="Unspecified" dataAnnotationsProductionModes="NoAnnotations, All" jsonOptions="EnableJson" outputName="HumanismeService" cfx:targetProject="..\Humanisme.webApi\Humanisme.webApi.csproj" cfx:targetProjectLayout="Update" produceProxy="False" />
    </cf:configuration>
  </cf:producer>

(....)

<cf:entity name="EtapaVital" namespace="Humanisme" categoryPath="/Humanisme">
    <cf:property name="Id" key="true" />
    <cf:property name="Nom" />
    <cf:property name="Idioma" typeName="{0}.EtapaVitalIdiomaCollection" relationPropertyName="Etapa" />
    <cf:property name="Documents" typeName="{0}.DocumentCollection" relationPropertyName="EtapaVital" />
  </cf:entity>

Отображает следующие атрибуты сериализации:

  1. RowVersion и EntityState получают атрибуты сериализации.
  2. EntityDisplayName — нет.

    [System.Runtime.Serialization.DataMemberAttribute(Order=2147483647)]
    private CodeFluent.Runtime.CodeFluentEntityState _entityState;
    
            public EtapaVital()
    
            [System.Runtime.Serialization.DataMemberAttribute()]
            public virtual string EntityKey
            {
                get
                {
                    return this.Id.ToString();
                }
                set
                {
                    this.Id = ((int)(ConvertUtilities.ChangeType(value, typeof(int), -1)));
                }
            }
    
            public virtual string EntityDisplayName
            {
                get
                {
                    return this.Nom;
                }
            }
    
            [System.Xml.Serialization.XmlElementAttribute(IsNullable=true)]
            [System.ComponentModel.DataObjectFieldAttribute(false, true)]
            [System.ComponentModel.TypeConverterAttribute(typeof(CodeFluent.Runtime.Design.ByteArrayConverter))]
            [System.Runtime.Serialization.DataMemberAttribute()]
            public byte[] RowVersion
            {
                get
                {
                    return this._rowVersion;
                }
                set
                {
                    if (((value != null) 
                                && (value.Length == 0)))
                    {
                        value = null;
                    }
                    this._rowVersion = value;
                    this.OnPropertyChanged(new System.ComponentModel.PropertyChangedEventArgs("RowVersion"));
                }
            }
    
            [System.ComponentModel.DefaultValueAttribute(((int)(-1)))]
            [System.Xml.Serialization.XmlElementAttribute(IsNullable=false, Type=typeof(int))]
            [System.ComponentModel.DataObjectFieldAttribute(true)]
           [System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue=false, Order=100)]
            public int Id
            {
                get
                {
                    return this._id;
                }
                set
                {
                    if ((System.Collections.Generic.EqualityComparer<int>.Default.Equals(value, this._id) == true))
                    {
                        return;
                    }
                    int oldKey = this._id;
                    this._id = value;
                    try
                    {
                        this.OnCollectionKeyChanged(oldKey);
                    }
                    catch (System.ArgumentException )
                    {
                        this._id = oldKey;
                        return;
                    }
                    this.EntityState = CodeFluent.Runtime.CodeFluentEntityState.Modified;
                    this.OnPropertyChanged(new System.ComponentModel.PropertyChangedEventArgs("Id"));
                }
            }
    
            [System.ComponentModel.DefaultValueAttribute(default(string))]
            [System.Xml.Serialization.XmlElementAttribute(IsNullable=true, Type=typeof(string))]
            [System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue=false, Order=200)]
            public string Nom
            {
                get
                {
                    return this._nom;
                }
                set
                {
                    this._nom = value;
                    this.EntityState = CodeFluent.Runtime.CodeFluentEntityState.Modified;
                    this.OnPropertyChanged(new System.ComponentModel.PropertyChangedEventArgs("Nom"));
                }
            }
    
            [System.Xml.Serialization.XmlIgnoreAttribute()]
            public Humanisme.EtapaVitalIdiomaCollection Idioma
            {
                get
                {
                    if ((this._idioma == null))
                    {
                        if (((this.Id == -1) 
                                    || (this.EntityState.Equals(CodeFluent.Runtime.CodeFluentEntityState.Created) == true)))
                        {
                            this._idioma = new Humanisme.EtapaVitalIdiomaCollection(this);
                            return this._idioma;
                        }
                        this._idioma = Humanisme.EtapaVitalIdiomaCollection.LoadByEtapa(this);
                    }
                    return this._idioma;
                }
            }
    
            [System.Xml.Serialization.XmlIgnoreAttribute()]
            public Humanisme.DocumentCollection Documents
            {
                get
                {
                    if ((this._documents == null))
                    {
                        if (((this.Id == -1) 
                                    || (this.EntityState.Equals(CodeFluent.Runtime.CodeFluentEntityState.Created) == true)))
                        {
                            this._documents = new Humanisme.DocumentCollection(null, this);
                            return this._documents;
                        }
                        this._documents = Humanisme.DocumentCollection.LoadByEtapaVital(this);
                    }
                    return this._documents;
                }
            }
    
    
            public virtual CodeFluent.Runtime.CodeFluentEntityState EntityState
            {
                get
                {
                    return this._entityState;
                }
                set
                {
                    if ((System.Collections.Generic.EqualityComparer<CodeFluent.Runtime.CodeFluentEntityState>.Default.Equals(value, this.EntityState) == true))
                    {
                        return;
                    }
                    if (((this._entityState == CodeFluent.Runtime.CodeFluentEntityState.ToBeDeleted) 
                                && (value == CodeFluent.Runtime.CodeFluentEntityState.Modified)))
                    {
                        return;
                    }
                    if (((this._entityState == CodeFluent.Runtime.CodeFluentEntityState.Created) 
                                && (value == CodeFluent.Runtime.CodeFluentEntityState.Modified)))
                    {
                        return;
                    }
                    this._entityState = value;
                    this.OnPropertyChanged(new System.ComponentModel.PropertyChangedEventArgs("EntityState"));
                }
            }
    

Кажется, что в окне «Свойства» поверхности модели нет связанных параметров, и я не могу найти теги или атрибуты xml в файле cfp.

Я буду очень признателен, если вы дадите мне какую-нибудь подсказку или ссылку, с чего начать изучение параметров модели CodeFluent, которые приводят к этим результатам в классах.

Еще раз спасибо, я действительно превращаюсь в энтузиаста CodeFluent!


person JoeCool    schedule 13.03.2016    source источник


Ответы (1)


Свойство RowVersion создается сущностями CodeFluent, поскольку для режима параллелизма установлено значение Optimistic (документация). . Если у вас нет последнего значения этого свойства, вы не сможете сохранить сущность (CodeFluentConcurrencyException). Поэтому это свойство необходимо сериализовать.

EntityDisplayName предназначен для пользовательского интерфейса. Его значение вычисляется из одного или нескольких свойств. Поэтому нет необходимости сериализовать его, поскольку вы можете вычислить его на стороне клиента.

В настоящее время нет атрибутов для изменения поведения сериализации для этих конкретных свойств. Однако вы можете написать собственный подпроизводитель для добавления/удаления атрибутов сериализации свойств. Вы найдете пример, который добавляет определенные атрибуты Json.NET к свойствам (GitHub)

Вот некоторые атрибуты для изменения поведения сериализации:

  • serializable (Сущность): определяет, помечен ли этот объект как сериализуемый.
  • serializeEntityKey (Entity): определяет, должен ли быть сериализован EntityKey.
  • serializeTypeName (Entity): определяет, должно ли быть сериализовано TypeName.
  • serializationMode (Свойство): документация
  • dataMember или includeInSerialization (Свойство) => Предпочтительно использовать serializationMode
  • serializationOrder (свойство): определяет порядок сортировки этого свойства при сериализации.
  • serializationNullable (свойство): определяет, можно ли пропустить свойство при сериализации.
  • serializePrivateMember (свойство): определяет, является ли частное поле несериализуемого свойства сериализуемым.
  • publicSerializationCallbacks (Проект): определяет, являются ли методы обратного вызова сериализации общедоступными (OnEntityDeserializing, OnEntityDeserialized и т. д.).
person meziantou    schedule 14.03.2016
comment
Как обычно: спасибо, Мезианту. Здорово, что вы делитесь своими знаниями с CodeFluent на этом сайте. - person JoeCool; 15.03.2016