0

我的模型包含以下实体:

  <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。我该如何解决这个问题?我不想在将实体添加到集合之前保存它。

4

1 回答 1

1

您必须通过 setType 属性告诉 CodeFluent 它必须使用列表而不是字典来处理订单。之后 CodeFluent 将不再使用 Add 和 Contains 方法的 Id 属性,但仍会检查 Add 方法中的值 0,因此您还必须添加一个 OnAfterCreate 规则来初始化 Id 属性:

  <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();
于 2016-01-13T14:11:00.423 回答