Behaviour of saving an entity

Thread is closed for posting
3 posts, 1 answers
  1. Edward
    Edward avatar
    45 posts
    Member since:
    Aug 2005

    Posted 24 Apr 2012 Link to this post


    I have a context with Visitors and I'm saving a new one and then retrieve it like:

    string name = "Rico " + guid;
    var b = new OADemo.Customer();
    b.Lastname = name;
    var sb = context.Customer.FirstOrDefault(x => x.Lastname == achternaam);

    sb will return null.  I'm adding the new one to the context and then i'm quering this context so I thought it would find this newly inserted guy. This is not the case. Do I always need to do SaveChanges first?


  2. Answer
    Viktor Zhivkov
    Viktor Zhivkov avatar
    324 posts

    Posted 25 Apr 2012 Link to this post

    Hi Edward,

    Yes, It is required to call SaveChanges() before querying newly created instances. Executing a query the way you have posted issues a database query. Since the changes are not yet committed to the database, the internal data reader does not include the new record in the results.

    If you insist on skipping the SaveChanges() method call, you can use FlushChanges() which will persist the changes to the database (this includes inserted, updated and deleted records), but leaves the database transaction uncommitted. Later you have to additionally commit or rollback the transaction. This approach gives greater control over the database operations, but introduces s bit of complexity.

    Here is our documentation about the Context API related to transactions and persistence. Check the SaveChanges, FlushChanges, ClearChanges and Refresh sections.

    If you have any additional questions about the Context API or OpenAccess in general do not hesitate to contact us again.

    Kind regards,
    Viktor Zhivkov
    the Telerik team
    Follow @OpenAccessORM Twitter channel to get first the latest updates on new releases, tips and tricks and sneak peeks at our product labs! 
  3. Edward
    Edward avatar
    45 posts
    Member since:
    Aug 2005

    Posted 25 Apr 2012 Link to this post

    pretty neat
Back to Top