简体   繁体   中英

Using Auto Increment with MySQL, NHibernate and C#

EDIT - It turns our the problem was completely unrelated to the primary key mapping - the errors were pointing me in the wrong direction in this particular instance.

I'm trying to have a simple auto_incremented primary key map to a property in c#. Here's my hbm mapping I have at the moment:

<class name="Lobby" table="lobby">
    <id name="Id" type="int" unsaved-value="null" >
        <column name="id" not-null="true"/>
        <generator class="identity"/>
    </id>

...

</class>

And here's my class:

public class Lobby
{
    public virtual int Id { get; set; }

    ...

}

The table is declared as follows:

CREATE TABLE IF NOT EXISTS `lobby`
(
    `id` INT(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,

    ...


)

When I try to create an object using the repository:

using (var session = mSessionFactory.OpenSession())
using (var transaction = session.BeginTransaction())
{
    session.Save(newEntry);
    transaction.Commit();
}

I get a PropertyTypeException:

Exception occurred getter of Lobby.Id> Object does not match target type.

I've tried changing the property to a long and a short and this hasn't helped. I've also tried making the column not auto_incremented and using the "increment" generator, but this generates an insert query that doesn't include the 'id' property, which then fails because the Primary Key needs to be set.

Can anyone see what I am doing wrong and are there any examples of how to do this properly?

int cannot be null. You can try unsaved-value="0" .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM