【发布时间】:2013-08-05 15:44:59
【问题描述】:
我最近不得不将一个项目从 MySQL 转移到 MSSQL。我在我的表的 id 列上使用IDENTITY(1,1) 以匹配 MySQL 的自动增量功能。
当我尝试插入一个对象时,我收到了这个错误:
[SQLServerException: Cannot insert explicit value for identity column in table 'categories' when IDENTITY_INSERT is set to OFF.]
现在经过一些研究,我发现这是因为我试图在我的表上插入我的 id(0) 的值。所以例如我有一个对象类别
case class Category(
id: Long = 0L,
name: String
)
object Category extends Table[Category]("categories"){
def name = column[String]("name", O.NotNull)
def id = column[Long]("id", O.PrimaryKey, O.AutoInc)
def * = id ~ name <> (Category.apply _, Category.unapply _)
def add(model:Category) = withSession{ implicit session =>
Category.insert(model)
}
def remove(id:Long) = withSession{implicit session =>
try{Some(Query(Category).filter(_.id === id).delete)}
catch{case _ => None}
}
}
有没有办法将我的对象插入数据库并忽略 0L 而 MSSQL 不会抛出 SQLException? MySQL 会忽略 id 的值并像没有收到 id 一样进行增量。 我真的不想用除了 id 之外的所有东西创建一个新的案例类。
【问题讨论】:
标签: sql-server scala slick