c# - GenericADOException 未处理无法插入

标签 c# sql-server nhibernate

我正在尝试将 NHibernate 与 ByCode 映射结合使用,但收效甚微。知道我做错了什么吗?

我的 table :

CREATE TABLE [dbo].[activities](
    [id] [int] IDENTITY(1,1) NOT NULL,
    [date] [bigint] NOT NULL,
    [userId] [int] NOT NULL,
    [customerJob] [int] NULL,
    [service] [int] NULL,
    [class] [int] NULL,
    [notes] [text] NULL,
    [billable] [tinyint] NOT NULL,
    [duration] [int] NOT NULL,
 CONSTRAINT [PK_activities_1] PRIMARY KEY CLUSTERED 
(
    [id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

我的类(class):

public class Activity {
    public virtual int Id { get; set; }
    public virtual long Date { get; set; }
    public virtual int Userid { get; set; }
    public virtual int? Customerjob { get; set; }
    public virtual int? Service { get; set; }
    public virtual int? Class { get; set; }
    public virtual string Notes { get; set; }
    public virtual byte Billable { get; set; }
    public virtual int Duration { get; set; }

    public static void Add(Activity activity) {
        using (ISession session = ApplicationContextSingleton.SessionFactory.OpenSession()) {
            using (ITransaction transaction = session.BeginTransaction()) {
                session.Save(activity);
                transaction.Commit();
            }
        }
    }
}

我的映射类:

namespace SimpleTimer.Maps
{
    public class ActivitiesMap : ClassMapping<Activity>
    {
        public ActivitiesMap()
        {
            Schema("dbo");
            Lazy(true);
            Id(x => x.Id, map => map.Generator(Generators.Identity));
            Property(x => x.Date, map => map.NotNullable(true));
            Property(x => x.Userid, map => map.NotNullable(true));
            Property(x => x.Customerjob);
            Property(x => x.Service);
            Property(x => x.Class);
            Property(x => x.Notes);
            Property(x => x.Billable, map => map.NotNullable(true));
            Property(x => x.Duration, map => map.NotNullable(true));
        }
    }
}

我用来管理 session 和配置的单例:

class ApplicationContextSingleton {
    private static Configuration configuration;
    private static ISessionFactory sessionFactory;

    public static Configuration NHConfiguration {
        get {
            if (configuration == null) {
                AppConfigure();
            }
            return configuration;
        }
    }

    public static ISessionFactory SessionFactory {
        get {
            if (sessionFactory == null) {
                AppConfigure();
            }
            return sessionFactory;
        }
    }

    private static void AppConfigure() {
        configuration = ConfigureNHibernate();
        sessionFactory = NHConfiguration.BuildSessionFactory();
    }

    private static Configuration ConfigureNHibernate() {
        // Create the object that will hold the configuration settings
        // and fill it with the information to access to the database
        NHibernate.Cfg.Configuration configuration = new NHibernate.Cfg.Configuration();
        configuration.Properties[NHibernate.Cfg.Environment.ConnectionProvider] = "NHibernate.Connection.DriverConnectionProvider";

        // These are the three lines of code to change in order to use another database
        configuration.Properties[NHibernate.Cfg.Environment.Dialect] = "NHibernate.Dialect.MsSql2000Dialect";
        configuration.Properties[NHibernate.Cfg.Environment.ConnectionDriver] = "NHibernate.Driver.SqlClientDriver";
        configuration.Properties[NHibernate.Cfg.Environment.ConnectionString] = System.Configuration.ConfigurationManager.ConnectionStrings["SimpleTimerDatabase.Properties.Settings.QTimerConnectionString"].ConnectionString;

        var mapping = GetMappings();
        configuration.AddDeserializedMapping(mapping, "NHSchemaTest");
        SchemaMetadataUpdater.QuoteTableAndColumns(configuration);

        return configuration;
    }

    private static HbmMapping GetMappings() {
        var mapper = new ModelMapper();
        mapper.AddMappings(Assembly.GetAssembly(typeof(ActivitiesMap)).GetExportedTypes());
        var mapping = mapper.CompileMappingForAllExplicitlyAddedEntities();

        return mapping;
    }
}

我用来保存事件的代码:

Activity a = new Activity();
a.Date = DateTime.Now.Ticks / TimeSpan.TicksPerSecond;
a.Userid = 1;
a.Notes = "Notes";
a.Billable = 1;
a.Duration = 60 * 60 * 3; //three hours

Activity.Add(a);
Console.WriteLine("Added Activity");

Activity.Add 上我得到这个异常:

GenericADOException was Unhandled: could not insert:
[SimpleTimer.Domain.Activity][SQL: INSERT INTO dbo.Activity ([Date], Userid, Customerjob, Service, [Class], Notes, Billable, Duration) VALUES (?, ?, ?, ?, ?, ?, ?, ?); select SCOPE_IDENTITY()]

知道我做错了什么吗?

最佳答案

这种异常通常有一个明确的答案......下面几行。我希望是这样的:

GenericADOException was Unhandled: could not insert: [SimpleTimer.Domain.Activity][SQL: INSERT INTO dbo.Activity ([Date], Userid, Customerjob, Service, [Class], Notes, Billable, Duration) VALUES (?, ?, ?, ?, ?, ?, ?, ?); select SCOPE_IDENTITY()] ...
... --> System.Data.SqlClient.SqlException: Cannot insert the value NULL into column 'ActivityId', table 'DBNAME.dbo.Activity'; column does not allow nulls. INSERT fails ....

正如我在上面试图展示的那样,最值得怀疑的是 IDENTITY 被关闭。只需应用这样的东西

ALTER TABLE [dbo].[Activity] ALTER COLUMN [ActivityId] int NOT NULL IDENTITY(1,1)

或者更改生成器:5.1.4.1. generator

关于c# - GenericADOException 未处理无法插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23024919/

相关文章:

sql - TSQL 月度报告按组求和

php - 无法将 SQLEXPRESS 与 Laravel 5.6 连接

sql-server - 使用 ASP.NET MVC 和 SQL Server 实现家谱的最佳方法是什么

linq - 通过NHibernate + Linq + Future获得计数

c# - LINQ2SQL 和 NHibernate,按计算列分组

c# - 在 C# 中从 SOAP 生成不同的异常

c# - 获取 SignalR 连接启动错误堆栈

asp.net - 加入 nhibernate 和 ASP.NET 成员/角色/配置文件服务的最佳实践

c# - 系统.Delegate System.Reflection.MethodInfo.CreateDelegate(System.Type)

c# - 单线程定时器