尝试使用 NPoco 在数据库中插入值时出错

我正在使用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();

                }


            }

        }

    }

}


波斯汪
浏览 98回答 1
1回答

大话西游666

Umbraco 论坛上的好人解决了我的问题。这是我的课堂上缺失的部分:[PrimaryKeyColumn(AutoIncrement = true, IdentitySeed = 1)]所以我的课程最终应该是这样的:[TableName("BlogComments")]&nbsp; &nbsp; [PrimaryKey("Id", AutoIncrement = true)]&nbsp; &nbsp; [ExplicitColumns]&nbsp; &nbsp; public class BlogCommentSchema&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; [PrimaryKeyColumn(AutoIncrement = true, IdentitySeed = 1)]&nbsp; &nbsp; &nbsp; &nbsp; [Column("Id")]&nbsp; &nbsp; &nbsp; &nbsp; public int Id { get; set; }&nbsp; &nbsp; &nbsp; &nbsp; [Column("BlogPostUmbracoId")]&nbsp; &nbsp; &nbsp; &nbsp; public int BlogPostUmbracoId { get; set; }&nbsp; &nbsp; &nbsp; &nbsp; [Column("Name")]&nbsp; &nbsp; &nbsp; &nbsp; public string Name { get; set; }&nbsp; &nbsp; &nbsp; &nbsp; [Column("Email")]&nbsp; &nbsp; &nbsp; &nbsp; public string Email { get; set; }&nbsp; &nbsp; &nbsp; &nbsp; [Column("Website")]&nbsp; &nbsp; &nbsp; &nbsp; public string Website { get; set; }&nbsp; &nbsp; &nbsp; &nbsp; [Column("Message")]&nbsp; &nbsp; &nbsp; &nbsp; [SpecialDbType(SpecialDbTypes.NTEXT)]&nbsp; &nbsp; &nbsp; &nbsp; public string Message { get; set; }&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP