0
votes

I'm using Fluent Nhibernate and my relevant entities are:

public class Product
{
    public virtual int ID {get; set;}
    public virtual string Name {get; set;}
    public virtual Supplier Supplier {get; set;}
}

public class Supplier
{
    public virtual int ID {get; set;}
    public virtual string Name {get; set;}
    public virtual List<Product> Products {get; set;}
}

In the mapping the supplier has HasMany on the Products + Inverse + Cascade.All in order to save all the prodcuts at once. My Product Primary Key and thus the equality members is the Id which is generated with NH sequence.

I need to create a list of products to a new supplier. Well if I add the products to the list before they get the primary key from the DB, only the first product being added to the list because the ID is 0 for all the products so the equals method return true, and the list "thinks" it already has that product.

I can save the products one by one before adding to the supplier list so the will get the Id value for the data base. But that doesn't use the cascade ability.

Any creative suggestion will be welcome.

2
why do you rely on id only when it comes to equality?wiero
@wiero, Because it's my primary key in the DB. why? what would you suggest in those cases?gdoron is supporting Monica
hi i did some research and i found this question stackoverflow.com/questions/2719877/… and i think this is good approach, for me it was not so obvious than two object can be considered equal depending only on db id, for example product with same name and supplier with diferent id will be different. this is an interesting problem :)wiero

2 Answers

2
votes

It's clear that you are intentionally breaking equality by doing a blind compare by Id.

I usually do not override Equals in my entities because it forces loading in some cases where it's not needed.

If you really want to do override Equals, you can do something like:

public override bool Equals(object obj)
{
    if (Id == 0)
        return ReferenceEquals(this, obj);
    return obj != null && Id == ((Entity)obj).Id;
}
0
votes

I dont know if I understood the question 100%, but anyhow:

We use a similiar approach where an Event has a list of Registrations. We do however, as you mentioned, save the registrations first before saving the actual event. This causes the N+1 problem when adding many registrations at once, but thats rarely the case for our scenario. Maybe that problem would go away if we used another id-generator such as HiLo? I dont know because we havent had the time to look into it.

When we delete a registration the cascade operation works successfully, and the registration collection of the event is properly updated.