使用persistenceIdentity时,在组合关系中将未保存的实体添加到集合会出错

时间:2016-01-09 20:44:58

标签: codefluent

我的模型包含以下实体:

  <cf:entity name="Order" cfom:bindingList="false">
    <!--persistenceIdentity is true, because the corresponding column for this property must be auto incremented by the database.-->
    <cf:property name="Id" typeName="ulong" key="true" persistenceIdentity="true" cfps:hint="CLUSTERED" />

    <!-- composition relation -->
    <cf:property name="Orderlines" typeName="{0}.OrderlineCollection" cascadeDelete="Before" cascadeSave="After" />

    <cf:method name="Save">
      <cf:rule typeName="transaction" transactionType="TransactionScope" timeout="00:60:00" scopeOption="Required" />
    </cf:method>
  </cf:entity>

  <cf:entity name="Orderline" cfom:bindingList="false">

    <!--persistenceIdentity is true, because the corresponding column for this property must be auto incremented by the database.-->
    <cf:property name="Id" typeName="ulong" key="true" persistenceIdentity="true" cfps:hint="CLUSTERED" />

    <!-- Relation back to indicate an 1-to-n composition relationship. -->
    <cf:property name="Order" typeName="{0}.Order" />
  </cf:entity>

我有以下代码:

  Order order = new Order();
  Orderline orderline = new Orderline();
  order.Orderlines.Add(orderline);  // ERROR
  order.Save();  // Save the order and its orderlines

将实体添加到集合时出错,因为Id属性包含值0.如何解决此问题?在将实体添加到集合之前,我不想保存实体。

1 个答案:

答案 0 :(得分:1)

您必须告诉CodeFluent它必须通过setType属性使用列表而不是字典作为订单行。之后CodeFluent将不再使用Add属性和Add包含方法,但仍然在Add方法中检查值0,因此您还必须添加初始化Id属性的OnAfterCreate规则:

  <cf:entity name="Orderline" cfom:bindingList="false" setType="List">

    <!--persistenceIdentity is true, because the corresponding column for this property must be auto incremented by the database.-->
    <cf:property name="Id" typeName="ulong" key="true" persistenceIdentity="true" cfps:hint="CLUSTERED" />

    <cf:property name="Name" typeName="string" />

    <!-- Relation back to indicate an 1-to-n composition relationship. -->
    <cf:property name="Order" typeName="{0}.Order" />

    <cf:rule typeName="OnAfterCreate" />
    <cf:snippet name="OnAfterCreate" language="CSharp">
      <!-- here or in a partial class -->
      private void OnAfterCreate()
      {
      this._id = long.MaxValue;
      }
    </cf:snippet>
  </cf:entity>

现在代码有效了。订单行将添加并保存在保存订单时创建的事务中。保存订单后,订单行已从数据库中获取其ID值:

  Order order = new Order();

  Orderline orderline = new Orderline();
  orderline.Name = "First order";
  order.Orderlines.Add(orderline);

  orderline = new Orderline();
  orderline.Name = "second order";
  order.Orderlines.Add(orderline);

  order.Save();