通过代码使用NHibernate映射:当IDENTITY_INSERT设置为OFF时,无法在表'DietUser'中为标识列插入显式值 [英] Using NHibernate mapping by code: Cannot insert explicit value for identity column in table 'DietUser' when IDENTITY_INSERT is set to OFF

查看:276
本文介绍了通过代码使用NHibernate映射:当IDENTITY_INSERT设置为OFF时,无法在表'DietUser'中为标识列插入显式值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

花些时间为我找到答案,以为我会分享爱意.

Took me a while to find an answer for this so thought I'd share the love.

在SQL Server中通过代码使用NHibernate的新映射时,我无法保存实体.保存实体时,将引发System.Data.SqlClient.SqlException并显示以下消息(减去表名):

When using NHibernate's new mapping by code with SQL Server I'm unable to save an entity. When saving an entity a System.Data.SqlClient.SqlException is thrown with the following message (minus the table name):

当IDENTITY_INSERT设置为OFF时,无法在表'DietUser'中为标识列插入显式值."

"Cannot insert explicit value for identity column in table 'DietUser' when IDENTITY_INSERT is set to OFF."

我的表使用身份ID,而实体&映射如下所示:

My table uses an identity ID and the entity & mappings look like this:

public class User
{
    public virtual int Id { get; set; }
    public virtual string Name { get; set; }
    public virtual string Username { get; set; }
    public virtual string Password { get; set; }
    public virtual short DailyPoints { get; set; }
}

public class UserMapping : ClassMapping<User>
{
    public UserMapping()
    {
        Id(x => x.Id);
        Property(x => x.Name);
        Property(x => x.Username);
        Property(x => x.Password);
        Property(x => x.DailyPoints);
    }
}

我知道如何使用XML映射来映射此映射,但是我想尽可能通过代码使用内置映射.

I know how I'd map this using XML mapping but I want to use the built-in mapping by code if at all possible.

推荐答案

在论坛上进行了一些挖掘之后,我很幸运,并找到了如何进行映射的方法.如果您要转至示例Fabio提供的示例,那是很棒的使用GUID作为ID或类似名称,但如果要使用身份ID(也看到了其他ID),则需要指定要使用的生成器.这是有效的我更新的映射:

After some digging around in the forums I got lucky and found how to map this. The example Fabio provides is great if you're going to use a GUID for an ID or something like that but if you want to use an identity ID (saw a bunch of others as well), you need to specify what generator you're going to use. Here's my updated mapping that works:

public class UserMapping : ClassMapping<User>
{
    public UserMapping()
    {
        Id(x => x.Id, map => map.Generator(Generators.Identity));
        Property(x => x.Name);
        Property(x => x.Username);
        Property(x => x.Password);
        Property(x => x.DailyPoints);
    }
}

这篇关于通过代码使用NHibernate映射:当IDENTITY_INSERT设置为OFF时,无法在表'DietUser'中为标识列插入显式值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆