2012-08-09 65 views
1

我已經創建了我想要收集於烏節路的數據庫中一些簡單的數據模塊果園CMS數據庫,所以我創建的模型,遷移和處理它:如何保存自定義數據

Models/StatePartRecord.cs

namespace Address.Models 
    { 
     public class StatePart : ContentPart<StatePartRecord> 
     { 
      public int Id 
      { 
       get { return Record.Id; } 
       set { Record.Id = value; } 
      } 
      public string StateName 
      { 
       get { return Record.StateName; } 
       set { Record.StateName = value; } 
      } 
     } 
    } 

Models/StatePartRecord.cs

namespace Address.Models 
{ 
    public class StatePartRecord : ContentPartRecord 
    { 
     public virtual int Id { get; set; } 
     public virtual string StateName { get; set; } 
    } 
} 

Migrations.cs

namespace Address 
{ 
    public class Migrations : DataMigrationImpl 
    { 
     public int Create() 
     { 
      SchemaBuilder.CreateTable("StatePartRecord", table => table 
       .ContentPartRecord() 
       .Column<string>("StateName") 
       ); 

      return 1; 
     } 
     public int UpdateFrom1() 
     { 
      ContentDefinitionManager.AlterPartDefinition("State", part => part 
       .Attachable()); 

      return 2; 
     } 

    } 
} 

Handlers/StatePartHandler.cs

namespace Address.Handlers 
{ 
    public class StatePartHandler : ContentHandler 
    { 
     public StatePartHandler(IRepository<StatePartRecord> repository) 
     { 
      Filters.Add(StorageFilter.For(repository)); 
     } 
    } 
} 

服務/ MyService.cs:

namespace Address.Services 
{ 
    public class AddressService : IAddressService 
    { 
    ... 
    public void InsertState(Models.StatePartRecord state) 
    { 
     _stateRepository.Create(state); 
    } 
    ... 
} 
現在

書面服務類爲我的模塊,當我嘗試創建一個項目並將其保存在數據庫中它trows an exeption:

attempted to assign id from null one-to-one property: ContentItemRecord 

_stateRepository是一個IRepository<StatePartRecord>類型的注入對象。

什麼是黃?

回答

2

這是因爲ContentPartRecord具有ContentItemRecord屬性,該屬性指向與ContentPartRecord的零件所附的內容項相對應的ContentItemRecord。

您不必直接管理部分記錄:烏節服務(主要是ContentManager)可以實現這個要求。即使您想修改較低級別的記錄,您也應該通過ContentManager(通過注入IContentManager)來完成此操作。只有在您用來存儲非內容數據(即非ContentPartRecords)的「普通」記錄時才能直接操作記錄。

 // MyType is a content type having StatePart attached 
     var item = _contentManager.New("MyType"); 

     // Setting parts is possible directly like this. 
     // NOTE that this is only possible if the part has a driver (even if it's empty)! 
     item.As<StatePart>().StateName = "California"; 

     _contentManager.Create(item); 
+0

感謝您的回答,我已經嘗試通過IContentManager.Create()來做到這一點,但它沒有工作,並且「無效的Cast Exeption」無效。我可以請你給我一個例子嗎? – 2012-08-10 10:00:01

+0

我已經添加了一個。請注意,你的部分應該有一個驅動程序! – Piedone 2012-08-11 18:36:33

+0

謝謝@Piedone。我添加了驅動程序,它完美的工作! 另一個問題是,如何使用ContentManager服務更新特定的contentitem? – 2012-08-14 08:17:15

相關問題