Fluent nHibernate no identity column in table

2019-05-07 19:45发布

问题:

How do I specify with fluent NHibernate mapping for a table that doesn't have an identity column?

I want something like this:

public sealed class CustomerNewMap : ClassMap<CustomerNew>, IMap
{
    public CustomerNewMap()
    {
        WithTable("customers_NEW");
        Not.LazyLoad();
        Not.Id(); // this is invalid...
        Map(x => x.Username);
        Map(x => x.Company);
    }
}

I mean no primary key defined in the database (not much defined in the database).

回答1:

I found the answer to be:

  public CustomerNewMap()
  {
        WithTable("customers_NEW");
        Not.LazyLoad();
        Id(x => x.Username).GeneratedBy.Assigned();
        Map(x => x.Company);
  }


回答2:

This doesn't directly answer the question.. but it answers the issue in the comment to the accepted answer here.

We had the same issue with a SQL View over our Ledger. The problem is that NHibernate will happily duplicate rows when the Id property isn't unique. In our case.. we had Ledger entries that had the CustomerAccountId set as the Id.. which wasn't unique within the view. To get around that.. I mapped a CompositeId that was based on whatever I could find that made the row unique. In our case, it was a combination of CustomerAccountId and WeekEnding:

CompositeId()
    .KeyProperty(x => x.CustomerAccountId)
    .KeyProperty(x => x.WeekEnding);

This was enough to have NHibernate not map duplicates.



回答3:

I found I had to explicitly set a column name in a similar case. Something like

  Id(x => x.Username).Column("Username").GeneratedBy.Assigned();