我创建了一个模块,我想在 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));
}
}
}
服务/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
请注意_stateRepository
是 IRepository<StatePartRecord>
输入类型的注入(inject)对象。
王是什么?
最佳答案
这是因为 ContentPartRecord 有一个 ContentItemRecord 属性,该属性指向与 ContentPartRecord 的 Part 附加到的内容项相对应的 ContentItemRecord。
您不必直接管理零件记录:Orchard 服务(主要是 ContentManager)会为您完成此操作。即使您想要修改较低级别的记录,您也应该通过 ContentManager 来完成此操作(通过注入(inject) 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);
关于c# - 如何在 Orchard CMS 数据库中保存自定义数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11880078/