context.savechanges impact - concept

2 posts, 0 answers
  1. tango
    tango avatar
    5 posts
    Member since:
    Oct 2014

    Posted 20 Oct 2015 Link to this post

    Dear Team,

    i am encountering a scenario that is as follows.

    i have two tables named parent and child.

    Upon fetching data from database, i got 1 row against parent and 2 rows against child.

    At this stage if i ​create new child and add it to context and apply save changes, so ​now my database contains 1 row against parent and 3 rows against child but my context only contains 2 rows against child...

    Do i need to refresh whole context or only that child to get latest database childs record in context so that i can do other operations with newly added child during the entire operation.

     

    Parent objparent = context.Parent( p => p.id = 4);
    objparent.count(); //1
    objparent.Child.count();//2
      
    Child objchild = new Child();
    objchild.name = "abc";
    objchild.parentid = 4;
      
    context.add(objchild);
    context.savechanges();
    //do i need to refresh whole context to have newly added child under given parent
    //or i should only fetch all childs against parent id 4 and re-attach them to context

     

  2. Doroteya
    Admin
    Doroteya avatar
    502 posts

    Posted 23 Oct 2015 Link to this post

    Hello tango,

    In general, the outcome you observe is expected; the database does not notify the application (and Data Access in particular) about the result from the committed transactions. If you need to obtain the most fresh data, you need to execute a new query after the call to the SaveChanges() method. For this purpose, you could modify your code following the pattern shown below:
    DataAccessModel.Category category = dbContext.Categories.First(c => c.CategoryID == 1);
    int prodsCount = category.Products.ToList().Count;
     
    DataAccessModel.Product product = new DataAccessModel.Product()
    {
        ProductName = "abc",
        Category = category
    };
     
    dbContext.Add(product);
    dbContext.SaveChanges();
     
    prodsCount = category.Products.Count;

    I would also recommend you the following sections from our documentation:
    - CRUD Operations regarding the retrieval of data from the database
    - Manage Navigation Properties regarding the handling of related database objects

    I hope this helps. Let us know if you need further information.


    Regards,
    Doroteya
    Telerik
     
    Check out the latest announcement about Telerik Data Access vNext as a powerful framework able to solve core development problems.
  3. DevCraft banner
Back to Top