views:

46

answers:

3

I've been struggling with this for 2 days now so i thought i would give it a shot here.

my scenario looks like this. i got a Customer and CustomerPhone. Now i save the Customer and CustomerPhone at the same time but the CustomerPhone doesn't get Id right away. but if i do a redirect to a other site and get the Customer object there the CustomerPhone will have a Id.

my code for the the classes look like this.

public virtual int Id { get; private set; }
    public virtual string Name { get; set; }
    public virtual string OrgNumber { get; set; }
    public virtual DateTime? CreateDate { get; set; }
    public virtual bool Active { get; set; }
    public virtual string Email { get; set; }

    public virtual IList<CustomerPhone> CustomerPhones { get; set; }

    public Customer()
    {
        CustomerPhones = new List<CustomerPhone>();
    }

    public virtual void AddCustomerPhones(CustomerPhone customerPhone)
    {
        customerPhone.Customer = this;
        CustomerPhones.Add(customerPhone);
    }

I use fluent nhibernate for the mapping, but I have had it looked at and it doesn't seem to be the problem.

If you have any thoughts on this please write because this is causing big problems for me.

+1  A: 

Without seeing your mappings I can only give general advice ... but I've encountered this before when NHibernate has some changes pending in its session. A call to session.Flush() will typically sort the "problem" out by persisting entities and obtaining the ID values.

Cheers, John

John Rayner
+2  A: 

It is because your session is probably request based. So at the end of your Request, it flushes automatically. Without flushing, your stuff just sits in the Nhib session, and is not added to the DB, hence it not having Id's that are generated IN the db. (I assume you are using identity for the primary keys)

Flush it manually and you will have the Ids.

Chad Ruppert
A: 

Thanks to both of you the session.Flush() was the issue. Chad thanks that you mentioned the end request cause that was exactly how i had it setup, that made me understand a whole lot now.

Dejan.S
No problem. Glad I could help. If you weren't aware, session per request is really the way it ought to be, and you are following best practice.
Chad Ruppert