Episerver – 为什么 属性 setter 被绕过?

Episerver – Why is property setter bypassed?

似乎内容模型 setter 在从内部创建时只被调用一次

SetDefaultValues(ContentType contentType)

我做了一些测试:

1.创建新区块

  1. 尝试使用 SetDefaultValues 中的某些值设置属性。
  2. 由于 setter 的实施,使用了其他值。
[ContentType(DisplayName = "SetterTestsBlock", GUID = "43ca7e93-6982-4b95-b073-c42af6ad2315", Description = "")]
public class SetterTestsBlock : BlockData
{
  public virtual string SomeVirtualStringProperty
  {
    get => this.GetPropertyValue(t => t.SomeVirtualStringProperty);
    set { this.SetPropertyValue(t => t.SomeVirtualStringProperty, "Ahoj1"); }      
  }

  public string SomeStringProperty
  {
    get => this.GetPropertyValue(t => t.SomeStringProperty);
    set { this.SetPropertyValue(t => t.SomeStringProperty, "Ahoj2"); }    
  }

  public override void SetDefaultValues(ContentType contentType)
  {
    SomeVirtualStringProperty = "Čau1";
    SomeStringProperty = "Čau2";
  }
} 

结果在意料之中

2。再次创建新区块

  1. 让 setters 抛出异常。
[ContentType(DisplayName = "SetterTestsBlock", GUID = "43ca7e93-6982-4b95-b073-c42af6ad2315", Description = "")]
public class SetterTestsBlock : BlockData
{
  public virtual string SomeVirtualStringProperty
  {
    get => this.GetPropertyValue(t => t.SomeVirtualStringProperty);
    //set { this.SetPropertyValue(t => t.SomeVirtualStringProperty, "Ahoj1"); }
    //set { }
    set { throw new Exception(); }
  }

  public string SomeStringProperty
  {
    get => this.GetPropertyValue(t => t.SomeStringProperty);
    //set { this.SetPropertyValue(t => t.SomeStringProperty, "Ahoj2"); }
    //set { }
    set { throw new Exception(); }
  }

  //public override void SetDefaultValues(ContentType contentType)
  //{
  //    SomeVirtualStringProperty = "Čau1";
  //    SomeStringProperty = "Čau2";
  //}
} 

这次的结果也是挺让人期待的

  1. 无默认值覆盖调用 = 无默认值,resp。也不例外。

3。将更改发布到测试 2

中的块
  1. 在 CMS 网络界面中输入一些值。
  2. 发布更改。

这个结果并不那么令人期待

  1. CMS 未显示任何错误,因此未引发异常。

总结

  1. 属性 setter 仅从 SetDefaultValues(ContentType contentType) 方法调用(在块首次创建期间)。
  2. 观察到的行为不依赖于 属性 虚拟性(virtual 修饰符)。

问题

想象下面的代码说明的情况。

[ContentType(DisplayName = "RealUsageSimulation", GUID = "12737925-ab51-4f63-9144-cd4632244a1c", Description = "")]
public class RealUsageSimulation : BlockData
{
  public string SomeStrPropWithDependency
  {
    get => this.GetPropertyValue(t => t.SomeStrPropWithDependency);
    set
    {
      this.SetPropertyValue(t => t.SomeStrPropWithDependency, GetDbStoreFormValue());
        
      string GetDbStoreFormValue()
      {  
         return string.Join(
           ",",
           value
             .Split(new[] { '♦', '♣', '♠'}, StringSplitOptions.RemoveEmptyEntries)
             .Select(x => x.Trim()));
      }
    }
  }
}

由于总结中描述的问题 setter 逻辑基本上是无用的。

我有什么地方错了吗?

我知道如何用其他正确的方法解决这个问题。 我只是想知道为什么没有调用setter。

属性 值不会通过模型 class' 属性 保存,例如,通过在编辑模式下编辑内容来保存内容(请记住:内容甚至可以保存如果内容类型 class 从代码中删除)。

之所以在SetDefaultValues中调用setter是因为你的代码使用了class属性。

对于您的情况,连接 ContentSaving 事件以在保存内容时进行任何 属性 值更改可能更合适。