Reputation: 7336
My Entity has no primary key for some reasons:
public partial class VehicleLocation
{
public virtual string UserCode { get; set; }
public virtual string DateTime { get; set; }
public virtual string Device { get; set; }
public virtual string Gps { get; set; }
public virtual string GpsDateTime { get; set; }
public virtual double Speed { get; set; }
}
The mapping:
class VehicleLoactionMap : ClassMap<VehicleLocation>
{
public VehicleLoactionMap()
{
Table("VEHICLE_LOCATION");
LazyLoad();
Map(x => x.UserCode).Column("USER_CODE");
Map(x => x.DateTime).Column("DATE_TIME");
Map(x => x.Device).Column("DEVICE");
Map(x => x.Gps).Column("GPS");
Map(x => x.GpsDateTime).Column("GPS_DATE_TIME");
Map(x => x.Speed).Column("SPEED");
}
}
I got this error:
The entity 'VehicleLocation' doesn't have an Id mapped...
How can I map my entity without using a primary key?
Upvotes: 7
Views: 18376
Reputation: 1199
Easy to create a composite key. Code sample (VB):
Table("Table1")
CompositeId().KeyProperty(Function(x) x.Field1).KeyProperty(Function(x) x.Field2)
Upvotes: 1
Reputation: 2003
There is no way of doing this as NHibernate requires a unique identifier for each entity. This is because NHibernate requires a way to tie a row of data in the database table to the entity. If it cannot do this then there is no way for it to perform any form of persistance on the entity data.
In situations where the table does not have a single primary key I have found two possible approaches to work.
Use a composite primary key.
If your DBMS supports you can use the physical row identifier. SQL Server 2008 has %%physloc%%
and Oracle has ROWID
.
But I would really not recommend option 2 in pretty much any scenario. This is because the DBMS makes no guarantees that the row id will stay the same over the lifetime of the row and is therefore a very un-reliable Primary Key.
Upvotes: 2
Reputation: 3281
I had the same issue a while back, but after a lot of searching I found that it is not possible to have entities without an identifier field to be mapped in nHibernate.
But you can do this by having composite keys instead of unique identifiers. Although I haven't tried it myself.
Here is an answer to a similar question that might help you.
Upvotes: 9