JT
JT

Reputation:

Fluent-NHibernate table mapping with no primary key

I am trying to create a mapping to a database table that has no primary keys/references.

public class TestMap : ClassMap<<Test>Test> {

    public TestMap() {

        WithTable("TestTable");

        Map(x => x.TestColumn);

    }

}

This fails and expects id or composite-id. Is this possible in fluent nhibernate?

Upvotes: 9

Views: 6460

Answers (6)

Apocatastasis
Apocatastasis

Reputation: 500

You can map an entity to a table without keys defined in the database. I do so in legacy SQL Server databases. However, the table must have a candidate key (some set of columns that actually stores a unique combination of values). The concept of entity involves the notion of some kind of identity. Instead of this, what you're trying in your code is to map an entity without identity, wich isn't possible.

Upvotes: 0

Stefan Steinegger
Stefan Steinegger

Reputation: 64628

If the table contains data that belongs to another entity, you could map it as a collection of components. Components are not identified by themselves, but they belong to another entity, which is identified.

Upvotes: 0

Jiss
Jiss

Reputation: 1

If we can bring a column from table having no primary key/identity coulmn, then we can use fluent as below:

Id(x => x.TempID).Column("TempID");

Upvotes: 0

Fourth
Fourth

Reputation: 9351

This functionality isn't supported by nhibernate as far as I know. As a general rule of thumb, however, you should really always have some kind of ID and if you find yourself in a situation where you think you don't need one you should assess your data model. An ID, whether it be a table-specific primary key, or a surrogate key from another table, should exist. This not only ensures that nhibernate can process the table, but helps performance via indexing.

Before you start assuming nhibernate isn't going to fulfill your needs, consider why you don't have a key on the table and what kind of sense it makes not to have one.

Upvotes: 0

Tompi
Tompi

Reputation: 296

In Oracle at least, I have used "ROWID" for this. For mssql you might use the "ROW_NUMBER()" builtin function for readonly access to the table, but I haven't tried that...

Upvotes: 6

Jamie Ide
Jamie Ide

Reputation: 49251

No. You'll have to add a surrogate primary key, such as an identity column in SQL Server, to map this table. As far as I know, this isn't supported by NHibernate itself.

Why don't you have a primary key on this table?

Upvotes: 2

Related Questions