简体   繁体   中英

Mapping custom GUID with Fluent NHibernate

I am using Fluent NHibernate to map an Oracle database. It is a legacy database so I cant really change everything I want.

There is a GUID field, but the keys are still composite (I will change this as soon as I can so that the keys are not composite, but I cant do it right now). The GUID is a VARCHAR2 field with this layout: 551608b1-275d-49f6-9561-44d01aacf23f . The GUID is not added by a sequence in Oracle, but inserted from code (C# or VB.net)

Guid.NewGuid()

I map the keys like this (VB.net):

With CompositeId()
   .KeyReference(Function(x) x.Well, "WellID")
   .KeyProperty(Function(x) x.GUID, "GUID")
   .KeyProperty(Function(x) x.SetDate, "SET_DATE")
End With

Or like this in C#

CompositeId()
   .KeyReference(x => x.Well, "WellID")
   .KeyProperty(x => x.GUID, "GUID")
   .KeyProperty(x => x.SetDate, "SET_DATE");

The mapping work great, and the object are just as I want them, until I need to save.

When I try to save or update a unchanged object

m_Session.SaveOrUpdate(obj)

I get : ORA-02289: sequence does not exist

Is the problem that I dont use a sequence to generate my GUID? How can I overcome this?

Using Guids "normally" In your entity the Id should be of type Guid:

public virtual Guid Id { get; private set; }

And in your ClassMap you should map it like this:

Id(x => x.Id) .Column("Id") .GeneratedBy.GuidComb();

This will use the recommended comb algorithm to generate new guids.

or

Id(x => x.Id) .Column("Id") .GeneratedBy.Guid();

to genertae new Guids using System.Guid or

Id(x => x.Id) .Column("Id") .GeneratedBy.GuidNative();

if you want to let the database generate the Guid for you.

EDIT: CompositeId does not have the GeneratedBy method as I thought, the source of the issue may be the mapping for the KeyReference method. Check the Well class mapping to ensure it is set to assigned since no native identity (Oracle sequence in your case) is valid for that id.

You need to tell NHibernate you are assigning the Id manually for that entity. Try something like the mapping shown below. Of course, when you create new instance of this entity you will need to set the appropriate values for GUID & SetDate in your code. You will also need to assign the appropriate Well class instance to the Well property.

CompositeId()
    .KeyReference(x => x.Well, "WellID")
    .KeyProperty(x => x.GUID, "GUID")
    .KeyProperty(x => x.SetDate, "SET_DATE")
    .GeneratedBy.Assigned();

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