当我保存一个对象时,NHibernate 尝试将对象保存在 id=0 的数据库中

When I saving an object, NHibernate tries to save object in database with id=0

我有 NHibernate --version 2.1.2.4000 并使用 NHibernate.Mapping.Attributes

当我想保存对象时,就像那样

session.SaveOrUpdate(car);
session.Flush(); 

我遇到异常 “当 IDENTITY_INSERT 设置为 OFF 时,无法在 table 'Car' 中为标识列插入显式值。”当 NHibernate 尝试设置 ID=0 的 sql 脚本时会发生这种情况,例如

"exec sp_executesql N'INSERT INTO Car (...., Id) VALUES (.., @p12)',N'...,@p12 int', @p12=0 go"

我的 class 具有以下属性

public class Car: ILifecycle {
    [Generator(Class = "identity")]
    [Id(0, Name = "Id", Column = "Id")]
    public virtual int Id { get; set; }  
    public virtual LifecycleVeto OnDelete(ISession s);
    public virtual void OnLoad(ISession s, object id);
    public virtual LifecycleVeto OnSave(ISession s);
    public virtual LifecycleVeto OnUpdate(ISession s);
}

Nhibernate helper 具有以下设置

public class NhibernateHelper {
        private readonly string _configurePath;
        /// <param name="path"></param>
        public NhibernateHelper(string path) {
            _configurePath = path;
        }
        /// <summary>The session factory.</summary>
        private static ISessionFactory SessionFactory;

        /// <summary>Gets current session.</summary>
        /// <returns>The current session.</returns>
        public static ISession GetCurrentSession() {
            return SessionFactory.OpenSession();
        }

        /// <summary>Connects to database 1.</summary>
        public void ConnectToDb() {

            var configuration = new Configuration();
            configuration.Configure(_configurePath);


            HbmSerializer.Default.Validate = true;
            Stream s = HbmSerializer.Default.Serialize(Assembly.GetExecutingAssembly());
            configuration.AddInputStream(s);
            
            var assembly = Assembly.Load("DAL");
            s = HbmSerializer.Default.Serialize(assembly);
            configuration.AddInputStream(s);

            SessionFactory = configuration.BuildSessionFactory();

        }
        public void CloseSessionFactory() {
            if (SessionFactory != null)
                SessionFactory.Close();
        }
    }

我忘记了属性前的数字。[Generator(1, Class = "identity")]