[英]When I saving an object, NHibernate tries to save object in database with id=0
I have NHibernate --version 2.1.2.4000 and use NHibernate.Mapping.Attributes我有 NHibernate --version 2.1.2.4000 并使用 NHibernate.Mapping.Attributes
When i want to save object, like that当我想保存对象时,就像那样
session.SaveOrUpdate(car);
session.Flush();
I have an exception "Cannot insert explicit value for identity column in table 'Car' when IDENTITY_INSERT is set to OFF."我有一个例外“当 IDENTITY_INSERT 设置为 OFF 时,无法为表 'Car' 中的标识列插入显式值。” This happens when NHibernate tries set sql script with ID=0, like that
当 NHibernate 尝试使用 ID=0 设置 sql 脚本时会发生这种情况,就像那样
"exec sp_executesql N'INSERT INTO Car (...., Id) VALUES (.., @p12)',N'...,@p12 int', @p12=0 go"
My class has the following attribute我的班级具有以下属性
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 has the following setting 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")]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.