2012-08-09 46 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