如何在Orchard CMS数据库中保存自定义数据

时间:2012-08-09 09:09:06

标签: c# asp.net-mvc-3 orchardcms

我创建了一个模块,我想在Orchard的数据库中收集一些简单的数据,所以我为它创建了模型,迁移和处理程序:

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));
        }
    }
}

Services / MyService.cs:

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

现在在我的模块的书面服务类中,当我尝试创建一个项目并将其保存在数据库中时,它会产生一个例外:

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

注意 _stateRepositoryIRepository<StatePartRecord>类型的注入对象。

什么是王?

1 个答案:

答案 0 :(得分:2)

这是因为ContentPartRecord有一个ContentItemRecord属性,该属性指向与ContentPartRecord的Part附加到的内容项对应的ContentItemRecord。

您不必直接管理部分记录:Orchard服务(主要是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);