Christian Horsdal
Christian Horsdal

Reputation: 4932

How can I create a UNIQUE constraint involving logic on two properties with Fluent NHibernate

I have class like this one:

public class Link
{
     public virtual long Id { get; set; }
     public virtual string IdentifierA { get; set; }
     public virtual string IdentifierB { get; set; }
}

and a mapping like this one:

public class LinkMap : ClassMap<Link>
{
    public LinkMap()
    {
        Id(x => x.Id);
        Map(x => x.IdentifierA);
        Map(x => x.IdentifierB);
    }
}

I would like to store only links, A, where there no link, B, in the database such that:

((A.IdentifierA == B.IndentifierA && A.IdentifierB == B.IdentifierB) || (A.IdentifierA == B.IndentifierB && A.IdentifierB == B.IdentifierA))

that is I consider any two links between two given identifiers as the same link, and only want to store one of them.

Can I set that up with Fluent NHibernate? If yes, how?

Upvotes: 0

Views: 218

Answers (1)

Firo
Firo

Reputation: 30813

You can define a database unique constraint

Map(x => x.IdentifierA).UniqueKey("Identifier_key");
Map(x => x.IdentifierB).UniqueKey("Identifier_key");

But in your scenario i think its better handled in code in one place. select if there exists an entity with the specified conditions and return it instead of saving a new one.

Upvotes: 1

Related Questions