0

我正在使用Umbraco 文档中的这个示例,当我尝试将值保存到数据库表时,我收到此错误:无法将值 NULL 插入列“Id”,表“petapoco.dbo.BlogComments”;列不允许空值。插入失败。该语句已终止。

此外,在创建表并在数据库中检查它之后,我可以看到没有为 id 字段设置主键和自动增量选项。

这就是我插入值的方式:

public class Class1 : IUserComposer
{
    public void Compose(Composition composition)
    {
       composition.Components().Append<SubscribeToContentServiceSavingComponent>();
    }
    public class SubscribeToContentServiceSavingComponent : IComponent
    {
        public void Initialize()
        {
            MemberService.Saved += MemberService_Saving;
        }

        public void Terminate()
        {
        }

        private void MemberService_Saving(IMemberService sender, SaveEventArgs<IMember> e)
        {
            foreach (IMember member in e.SavedEntities)
            {
                var blogPostToAdd = new BlogCommentSchema();

                blogPostToAdd.BlogPostUmbracoId = member.Id;
                blogPostToAdd.Name = member.Name;
                blogPostToAdd.Email = member.Name;
                blogPostToAdd.Website = member.Name;
                blogPostToAdd.Message = member.Name;

                using (var scope = Current.ScopeProvider.CreateScope(autoComplete:true))
                {
                    var database = scope.Database;
                    // use database  
                    scope.Database.Insert<BlogCommentSchema>(blogPostToAdd);
                    scope.Complete();
                }

            }
        }
    }
}
4

1 回答 1

1

Umbraco 论坛上的好人解决了我的问题。这是我班上缺少的部分:

[PrimaryKeyColumn(AutoIncrement = true, IdentitySeed = 1)]

所以我的课最终应该是这样的:

[TableName("BlogComments")]
    [PrimaryKey("Id", AutoIncrement = true)]
    [ExplicitColumns]
    public class BlogCommentSchema
    {
        [PrimaryKeyColumn(AutoIncrement = true, IdentitySeed = 1)]
        [Column("Id")]
        public int Id { get; set; }

        [Column("BlogPostUmbracoId")]
        public int BlogPostUmbracoId { get; set; }

        [Column("Name")]
        public string Name { get; set; }

        [Column("Email")]
        public string Email { get; set; }

        [Column("Website")]
        public string Website { get; set; }

        [Column("Message")]
        [SpecialDbType(SpecialDbTypes.NTEXT)]
        public string Message { get; set; }
    }
}
于 2019-08-26T13:57:10.880 回答