This is a migrated thread and some comments may be shown as answers.

context.savechanges impact - concept

1 Answer 41 Views
General Discussions
This is a migrated thread and some comments may be shown as answers.
This question is locked. New answers and comments are not allowed.
tango
Top achievements
Rank 1
tango asked on 20 Oct 2015, 03:06 PM

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

 

1 Answer, 1 is accepted

Sort by
0
Doroteya
Telerik team
answered on 23 Oct 2015, 02:49 PM
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.
Tags
General Discussions
Asked by
tango
Top achievements
Rank 1
Answers by
Doroteya
Telerik team
Share this question
or