none
Problems with Entity Famework and bindingsources

    Question

  • Hello !
    i'm using vb.net 2017 with EF 6
    I have 2 tables on my database : Product and ProductDetail
    I have also 2 bindingsource Productbindingsource and ProductDetailsbindingsource.
    I have also 2 datagridview each of them bound to the respective bindingsource.
    When the user select a product in the first datagridview , the other datagridview is filled with Productdetails for the selected product.
    I have this code :

    Private sub Fill_Product
    context.Products.Where(Function(t2) t2.cl>5).Load
    ProductBindingsource.datasource=context.Products.Local.ToBindinglist
    End sub
    
    Private Sub ProductBindingSource_CurrentChanged(sender As Object, e As  EventArgs) Handles ProductBindingSource.CurrentChanged
    
    context.Entry(ProductBindingSource.Current).Collection("ProductDetails").Load()
        ProductDetailsBindingsource.Datasource=DirectCast(ProductBindingSource.Current, Product).ProductDetails
    End sub
    
      Private Sub RollBack()
        Dim changedEntries = context.ChangeTracker.Entries().Where(Function(x) x.State <> EntityState.Unchanged).ToList()
        For Each entry In changedEntries
    
            Select Case entry.State
                Case EntityState.Modified
                    entry.CurrentValues.SetValues(entry.OriginalValues)
                    entry.State = EntityState.Unchanged
                Case EntityState.Added
                    entry.State = EntityState.Detached
                Case EntityState.Deleted
                    entry.State = EntityState.Unchanged
            End Select
        Next
    End Sub


    
    


    I have 2 problems with this code :
    1.when I delete a ProductDetail from the second Grid , and after execute the rollback Sub , the deleted ProductDetail is not back on that datagrid , andalso when I add new Productdetail when I rollback this is not removed from the gridview.( other modifications in values , are reverted to original values).

    2.On the sub ProductBindingSource_CurrentChanged , everytime that the user select a product in the first grid , the second grid is filled with ProductDetails and database is queried with .Load. But this is ok when the user select a Product for the first time . What about when the user select a Product for the second or third time ? The product Details are already loaded , so what to do to not query again from database but use local data ?


    Thank you !



    • Edited by dcode25 Thursday, December 6, 2018 12:41 PM
    Thursday, December 6, 2018 11:23 AM

All replies

  • Have you tried using the BindingSource Filter rather than using a Where?

    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    Thursday, December 6, 2018 12:06 PM
    Moderator
  • Have you tried using the BindingSource Filter rather than using a Where?

    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites


    sorry , I've modified my code.
    Thursday, December 6, 2018 12:19 PM
  • Have you tried using the BindingSource Filter rather than using a Where?


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites


    sorry , I've modified my code.
    I don't see the filter and why are you loading data on CurrentChange?

    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    Thursday, December 6, 2018 12:24 PM
    Moderator
  • Have you tried using the BindingSource Filter rather than using a Where?


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites


    sorry , I've modified my code.

    I don't see the filter and why are you loading data on CurrentChange?

    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    when the user select a product in first datagridview , I want to fill the second datagrid with ProductDetails. The currentchange event is fired when user select a product from first datagridview , so here I fill the data for ProductDetails bindingsource.

    I'm not included the filter because I modified my code. Pleas can you read again my case ? Thank you !

    Thursday, December 6, 2018 12:28 PM
  • Okay, let's look at it a tad differently than from my last replies. The following uses EF6 and NorthWind Microsoft database. I load a ListBox with Order Id (yeah it's not a DataGridView but we are only needing the order id to get order details records).

    NOTE: I did this in C# and converted to VB.NET

    Focus on the BindingSource PositionChanges where I get the order id and pass it to a sub HandleChanges which returns a List(Of OrderDetail) for the current order id and sets it to a DataGridView DataSource.

    Partial Public Class Form1
    	Private _bsOrders As New BindingSource()
    	Private _bsOrderDetails As New BindingSource()
    
    	Public Function GetOrders(ByVal pIdentifier As Integer) As List(Of OrderDetail)
    		Using context = New NorthWindEntities()
    			Return context.OrderDetails.Where(Function(item) item.OrderID = pIdentifier).ToList()
    		End Using
    	End Function
    	Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs)
    		Using context = New NorthWindEntities()
    			_bsOrders.DataSource = context.OrderDetails.Select(Function(ordDetails) ordDetails.OrderID.ToString()).ToList()
    			listBox1.DataSource = _bsOrders
    			AddHandler _bsOrders.PositionChanged, AddressOf _bsOrders_PositionChanged
    			HandlePositionChanges()
    			dataGridView1.AutoGenerateColumns = False
    			dataGridView1.DataSource = _bsOrderDetails
    		End Using
    	End Sub
    	Private Sub HandlePositionChanges()
    		_bsOrderDetails.DataSource = GetOrders(Convert.ToInt32(Convert.ToString(_bsOrders.Current)))
    	End Sub
    	Private Sub _bsOrders_PositionChanged(ByVal sender As Object, ByVal e As EventArgs)
    		HandlePositionChanges()
    	End Sub
    End Class
    

    The original C# code 

    public partial class Form1 : Form
    {
        public Form1() 
        {
            InitializeComponent();
        }
        private BindingSource _bsOrders = new BindingSource();
        private BindingSource _bsOrderDetails = new BindingSource();
    
        public List<OrderDetail> GetOrders(int pIdentifier) 
        {
            using (var context = new NorthWindEntities())
            {
                return context.OrderDetails.Where(item => item.OrderID == pIdentifier).ToList();
            }
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            using (var context = new NorthWindEntities())
            {
                _bsOrders.DataSource = context.OrderDetails.Select(ordDetails => ordDetails.OrderID.ToString()).ToList();
                listBox1.DataSource = _bsOrders;
                _bsOrders.PositionChanged += _bsOrders_PositionChanged;
                HandlePositionChanges();
                dataGridView1.AutoGenerateColumns = false;
                dataGridView1.DataSource = _bsOrderDetails;
            }
        }
        private void HandlePositionChanges()
        {
            _bsOrderDetails.DataSource = GetOrders(Convert.ToInt32(Convert.ToString(_bsOrders.Current)));
        }
        private void _bsOrders_PositionChanged(object sender, EventArgs e)
        {
            HandlePositionChanges();
        }
    }
    

    And it's very fast.


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    Thursday, December 6, 2018 1:14 PM
    Moderator
  • Okay, let's look at it a tad differently than from my last replies. The following uses EF6 and NorthWind Microsoft database. I load a ListBox with Order Id (yeah it's not a DataGridView but we are only needing the order id to get order details records).

    NOTE: I did this in C# and converted to VB.NET

    Focus on the BindingSource PositionChanges where I get the order id and pass it to a sub HandleChanges which returns a List(Of OrderDetail) for the current order id and sets it to a DataGridView DataSource.

    Partial Public Class Form1
    	Private _bsOrders As New BindingSource()
    	Private _bsOrderDetails As New BindingSource()
    
    	Public Function GetOrders(ByVal pIdentifier As Integer) As List(Of OrderDetail)
    		Using context = New NorthWindEntities()
    			Return context.OrderDetails.Where(Function(item) item.OrderID = pIdentifier).ToList()
    		End Using
    	End Function
    	Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs)
    		Using context = New NorthWindEntities()
    			_bsOrders.DataSource = context.OrderDetails.Select(Function(ordDetails) ordDetails.OrderID.ToString()).ToList()
    			listBox1.DataSource = _bsOrders
    			AddHandler _bsOrders.PositionChanged, AddressOf _bsOrders_PositionChanged
    			HandlePositionChanges()
    			dataGridView1.AutoGenerateColumns = False
    			dataGridView1.DataSource = _bsOrderDetails
    		End Using
    	End Sub
    	Private Sub HandlePositionChanges()
    		_bsOrderDetails.DataSource = GetOrders(Convert.ToInt32(Convert.ToString(_bsOrders.Current)))
    	End Sub
    	Private Sub _bsOrders_PositionChanged(ByVal sender As Object, ByVal e As EventArgs)
    		HandlePositionChanges()
    	End Sub
    End Class

    The original C# code 

    public partial class Form1 : Form
    {
        public Form1() 
        {
            InitializeComponent();
        }
        private BindingSource _bsOrders = new BindingSource();
        private BindingSource _bsOrderDetails = new BindingSource();
    
        public List<OrderDetail> GetOrders(int pIdentifier) 
        {
            using (var context = new NorthWindEntities())
            {
                return context.OrderDetails.Where(item => item.OrderID == pIdentifier).ToList();
            }
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            using (var context = new NorthWindEntities())
            {
                _bsOrders.DataSource = context.OrderDetails.Select(ordDetails => ordDetails.OrderID.ToString()).ToList();
                listBox1.DataSource = _bsOrders;
                _bsOrders.PositionChanged += _bsOrders_PositionChanged;
                HandlePositionChanges();
                dataGridView1.AutoGenerateColumns = false;
                dataGridView1.DataSource = _bsOrderDetails;
            }
        }
        private void HandlePositionChanges()
        {
            _bsOrderDetails.DataSource = GetOrders(Convert.ToInt32(Convert.ToString(_bsOrders.Current)));
        }
        private void _bsOrders_PositionChanged(object sender, EventArgs e)
        {
            HandlePositionChanges();
        }
    }

    And it's very fast.


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    THANK YOU  , but your code does not resolve my 2 problems that I've described above. did you try my code for rollback changes ? and what about the other problem with loading from database and read from local ?
    Thursday, December 6, 2018 1:28 PM
  • I didn't address your other things as I'm leaving for work and if not the case I would had address them but I have a very long day ahead of me and don't care to rush. At one time or another I've handles all the issues you've had but again no time today.

    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    Thursday, December 6, 2018 1:37 PM
    Moderator
  • Okay I found a minute to address the other issues. Assuming you got the RollBack from here, I like the Reload method rather than the posted marked answered.

    The following uses the Reload method for a rollback and note no save has been issued.

    Imports System
    Imports System.Collections.Generic
    Imports System.Linq
    Imports System.Windows.Forms
    Imports EntityState = System.Data.Entity.EntityState
    
    Partial Public Class Form1
    	Inherits Form
    
    	Public Sub New()
    		InitializeComponent()
    	End Sub
    	Private ReadOnly _bsOrders As New BindingSource()
    	Private ReadOnly _bsOrderDetails As New BindingSource()
    	Private ReadOnly _northWindEntities As New NorthWindEntities()
    
    	Public Function GetOrders(ByVal pIdentifier As Integer) As List(Of OrderDetail)
    		Return _northWindEntities.OrderDetails.Where(Function(item) item.OrderID = pIdentifier).ToList()
    	End Function
    	Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs)
    		_northWindEntities.ChangeTracker.DetectChanges()
    
    		_bsOrders.DataSource = _northWindEntities.OrderDetails.Select(Function(ordDetails) ordDetails.OrderID.ToString()).Distinct().ToList()
    
    		listBox1.DataSource = _bsOrders
    		AddHandler _bsOrders.PositionChanged, AddressOf _bsOrders_PositionChanged
    		HandlePositionChanges()
    
    		dataGridView1.AutoGenerateColumns = False
    		dataGridView1.DataSource = _bsOrderDetails
    
    	End Sub
    	Private Sub HandlePositionChanges()
    		_bsOrderDetails.DataSource = GetOrders(Convert.ToInt32(Convert.ToString(_bsOrders.Current)))
    	End Sub
    	Private Sub _bsOrders_PositionChanged(ByVal sender As Object, ByVal e As EventArgs)
    		HandlePositionChanges()
    	End Sub
    	''' <summary>
    	''' Check for unchanged entities only
    	''' </summary>
    	''' <param name="sender"></param>
    	''' <param name="e"></param>
    	Private Sub button2_Click(ByVal sender As Object, ByVal e As EventArgs)
    		Dim changedEntries = _northWindEntities.ChangeTracker.Entries().Where(Function(x) x.State = EntityState.Unchanged).ToList()
    
    
    		Console.WriteLine(changedEntries.Count)
    	End Sub
    	''' <summary>
    	''' Change current Quantity value
    	''' </summary>
    	''' <param name="sender"></param>
    	''' <param name="e"></param>
    	Private Sub button3_Click(ByVal sender As Object, ByVal e As EventArgs)
    		Dim current = CType(_bsOrderDetails.Current, OrderDetail)
    		current.Quantity = 9 ' being lazing to edit in the DataGridView
    		_bsOrderDetails.ResetBindings(False)
    	End Sub
    	''' <summary>
    	''' Revert current to original
    	''' </summary>
    	''' <param name="sender"></param>
    	''' <param name="e"></param>
    	Private Sub button1_Click(ByVal sender As Object, ByVal e As EventArgs)
    		_northWindEntities.Entry(CType(_bsOrderDetails.Current, OrderDetail)).Reload()
    	End Sub
    End Class
    
    


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    Thursday, December 6, 2018 3:34 PM
    Moderator
  • but the problem is that I don't want to read again from database. For that i'm using the reload sub.
    Thursday, December 6, 2018 3:55 PM
  • but the problem is that I don't want to read again from database. For that i'm using the reload sub.

    Okay but your RollBack work for me so I can't tell you why it's not working for you.

    I used the code in Button4 to call the rollback after maing several changes and afterwards checked for changes and there were none.

    Imports System
    Imports System.Collections.Generic
    Imports System.Linq
    Imports System.Windows.Forms
    Imports EntityState = System.Data.Entity.EntityState
    
    
    Partial Public Class Form1
    	Inherits Form
    
    	Public Sub New()
    		InitializeComponent()
    	End Sub
    	Private ReadOnly _bsOrders As New BindingSource()
    	Private ReadOnly _bsOrderDetails As New BindingSource()
    	Private ReadOnly _northWindEntities As New NorthWindEntities()
    
    	Public Function GetOrders(ByVal pIdentifier As Integer) As List(Of OrderDetail)
    		Return _northWindEntities.OrderDetails.Where(Function(item) item.OrderID = pIdentifier).ToList()
    	End Function
    	Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs)
    		_northWindEntities.ChangeTracker.DetectChanges()
    
    		_bsOrders.DataSource = _northWindEntities.OrderDetails.Select(Function(ordDetails) ordDetails.OrderID.ToString()).Distinct().ToList()
    
    		listBox1.DataSource = _bsOrders
    		AddHandler _bsOrders.PositionChanged, AddressOf _bsOrders_PositionChanged
    		HandlePositionChanges()
    
    		dataGridView1.AutoGenerateColumns = False
    		dataGridView1.DataSource = _bsOrderDetails
    
    	End Sub
    	Private Sub HandlePositionChanges()
    		_bsOrderDetails.DataSource = GetOrders(Convert.ToInt32(Convert.ToString(_bsOrders.Current)))
    	End Sub
    	Private Sub _bsOrders_PositionChanged(ByVal sender As Object, ByVal e As EventArgs)
    		HandlePositionChanges()
    	End Sub
    	''' <summary>
    	''' Check for unchanged entities only
    	''' </summary>
    	''' <param name="sender"></param>
    	''' <param name="e"></param>
    	Private Sub button2_Click(ByVal sender As Object, ByVal e As EventArgs)
    		Dim changedEntries = _northWindEntities.ChangeTracker.Entries().Where(Function(x) x.State = EntityState.Unchanged).ToList()
    
    
    		Console.WriteLine(changedEntries.Count)
    	End Sub
    	''' <summary>
    	''' Change current Quantity value
    	''' </summary>
    	''' <param name="sender"></param>
    	''' <param name="e"></param>
    	Private Sub button3_Click(ByVal sender As Object, ByVal e As EventArgs)
    		Dim current = CType(_bsOrderDetails.Current, OrderDetail)
    		current.Quantity = 9 ' being lazing to edit in the DataGridView
    		_bsOrderDetails.ResetBindings(False)
    	End Sub
    	''' <summary>
    	''' Revert current to original
    	''' </summary>
    	''' <param name="sender"></param>
    	''' <param name="e"></param>
    	Private Sub button1_Click(ByVal sender As Object, ByVal e As EventArgs)
    		_northWindEntities.Entry(CType(_bsOrderDetails.Current, OrderDetail)).Reload()
    	End Sub
    	Public Sub RollBack()
    		Dim context = _northWindEntities
    		Dim changedEntries = context.ChangeTracker.Entries().Where(Function(x) x.State <> EntityState.Unchanged).ToList()
    
    		For Each entry In changedEntries
    			Select Case entry.State
    				Case EntityState.Modified
    					entry.CurrentValues.SetValues(entry.OriginalValues)
    					entry.State = EntityState.Unchanged
    				Case EntityState.Added
    					entry.State = EntityState.Detached
    				Case EntityState.Deleted
    					entry.State = EntityState.Unchanged
    			End Select
    		Next entry
    	End Sub
    
    	Private Sub button4_Click(ByVal sender As Object, ByVal e As EventArgs)
    		RollBack()
    	End Sub
    End Class
    
    


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    Thursday, December 6, 2018 4:25 PM
    Moderator
  • but the problem is that I don't want to read again from database. For that i'm using the reload sub.

    Okay but your RollBack work for me so I can't tell you why it's not working for you.

    I used the code in Button4 to call the rollback after maing several changes and afterwards checked for changes and there were none.

    Imports System
    Imports System.Collections.Generic
    Imports System.Linq
    Imports System.Windows.Forms
    Imports EntityState = System.Data.Entity.EntityState
    
    
    Partial Public Class Form1
    	Inherits Form
    
    	Public Sub New()
    		InitializeComponent()
    	End Sub
    	Private ReadOnly _bsOrders As New BindingSource()
    	Private ReadOnly _bsOrderDetails As New BindingSource()
    	Private ReadOnly _northWindEntities As New NorthWindEntities()
    
    	Public Function GetOrders(ByVal pIdentifier As Integer) As List(Of OrderDetail)
    		Return _northWindEntities.OrderDetails.Where(Function(item) item.OrderID = pIdentifier).ToList()
    	End Function
    	Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs)
    		_northWindEntities.ChangeTracker.DetectChanges()
    
    		_bsOrders.DataSource = _northWindEntities.OrderDetails.Select(Function(ordDetails) ordDetails.OrderID.ToString()).Distinct().ToList()
    
    		listBox1.DataSource = _bsOrders
    		AddHandler _bsOrders.PositionChanged, AddressOf _bsOrders_PositionChanged
    		HandlePositionChanges()
    
    		dataGridView1.AutoGenerateColumns = False
    		dataGridView1.DataSource = _bsOrderDetails
    
    	End Sub
    	Private Sub HandlePositionChanges()
    		_bsOrderDetails.DataSource = GetOrders(Convert.ToInt32(Convert.ToString(_bsOrders.Current)))
    	End Sub
    	Private Sub _bsOrders_PositionChanged(ByVal sender As Object, ByVal e As EventArgs)
    		HandlePositionChanges()
    	End Sub
    	''' <summary>
    	''' Check for unchanged entities only
    	''' </summary>
    	''' <param name="sender"></param>
    	''' <param name="e"></param>
    	Private Sub button2_Click(ByVal sender As Object, ByVal e As EventArgs)
    		Dim changedEntries = _northWindEntities.ChangeTracker.Entries().Where(Function(x) x.State = EntityState.Unchanged).ToList()
    
    
    		Console.WriteLine(changedEntries.Count)
    	End Sub
    	''' <summary>
    	''' Change current Quantity value
    	''' </summary>
    	''' <param name="sender"></param>
    	''' <param name="e"></param>
    	Private Sub button3_Click(ByVal sender As Object, ByVal e As EventArgs)
    		Dim current = CType(_bsOrderDetails.Current, OrderDetail)
    		current.Quantity = 9 ' being lazing to edit in the DataGridView
    		_bsOrderDetails.ResetBindings(False)
    	End Sub
    	''' <summary>
    	''' Revert current to original
    	''' </summary>
    	''' <param name="sender"></param>
    	''' <param name="e"></param>
    	Private Sub button1_Click(ByVal sender As Object, ByVal e As EventArgs)
    		_northWindEntities.Entry(CType(_bsOrderDetails.Current, OrderDetail)).Reload()
    	End Sub
    	Public Sub RollBack()
    		Dim context = _northWindEntities
    		Dim changedEntries = context.ChangeTracker.Entries().Where(Function(x) x.State <> EntityState.Unchanged).ToList()
    
    		For Each entry In changedEntries
    			Select Case entry.State
    				Case EntityState.Modified
    					entry.CurrentValues.SetValues(entry.OriginalValues)
    					entry.State = EntityState.Unchanged
    				Case EntityState.Added
    					entry.State = EntityState.Detached
    				Case EntityState.Deleted
    					entry.State = EntityState.Unchanged
    			End Select
    		Next entry
    	End Sub
    
    	Private Sub button4_Click(ByVal sender As Object, ByVal e As EventArgs)
    		RollBack()
    	End Sub
    End Class
    


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites


    I've noticed that you are using tolist for the query that fill your datasource. i'm using local.tobindinglist. My idea that as described in my Problem 2 , is that to detect in any way that if a child entities is loaded from database , to use from local , otherwise to query the database.as I can see your are querying everytime the database. 
    Thursday, December 6, 2018 4:47 PM
  • but the problem is that I don't want to read again from database. For that i'm using the reload sub.

    Okay but your RollBack work for me so I can't tell you why it's not working for you.

    I used the code in Button4 to call the rollback after maing several changes and afterwards checked for changes and there were none.

    Imports System
    Imports System.Collections.Generic
    Imports System.Linq
    Imports System.Windows.Forms
    Imports EntityState = System.Data.Entity.EntityState
    
    
    Partial Public Class Form1
    	Inherits Form
    
    	Public Sub New()
    		InitializeComponent()
    	End Sub
    	Private ReadOnly _bsOrders As New BindingSource()
    	Private ReadOnly _bsOrderDetails As New BindingSource()
    	Private ReadOnly _northWindEntities As New NorthWindEntities()
    
    	Public Function GetOrders(ByVal pIdentifier As Integer) As List(Of OrderDetail)
    		Return _northWindEntities.OrderDetails.Where(Function(item) item.OrderID = pIdentifier).ToList()
    	End Function
    	Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs)
    		_northWindEntities.ChangeTracker.DetectChanges()
    
    		_bsOrders.DataSource = _northWindEntities.OrderDetails.Select(Function(ordDetails) ordDetails.OrderID.ToString()).Distinct().ToList()
    
    		listBox1.DataSource = _bsOrders
    		AddHandler _bsOrders.PositionChanged, AddressOf _bsOrders_PositionChanged
    		HandlePositionChanges()
    
    		dataGridView1.AutoGenerateColumns = False
    		dataGridView1.DataSource = _bsOrderDetails
    
    	End Sub
    	Private Sub HandlePositionChanges()
    		_bsOrderDetails.DataSource = GetOrders(Convert.ToInt32(Convert.ToString(_bsOrders.Current)))
    	End Sub
    	Private Sub _bsOrders_PositionChanged(ByVal sender As Object, ByVal e As EventArgs)
    		HandlePositionChanges()
    	End Sub
    	''' <summary>
    	''' Check for unchanged entities only
    	''' </summary>
    	''' <param name="sender"></param>
    	''' <param name="e"></param>
    	Private Sub button2_Click(ByVal sender As Object, ByVal e As EventArgs)
    		Dim changedEntries = _northWindEntities.ChangeTracker.Entries().Where(Function(x) x.State = EntityState.Unchanged).ToList()
    
    
    		Console.WriteLine(changedEntries.Count)
    	End Sub
    	''' <summary>
    	''' Change current Quantity value
    	''' </summary>
    	''' <param name="sender"></param>
    	''' <param name="e"></param>
    	Private Sub button3_Click(ByVal sender As Object, ByVal e As EventArgs)
    		Dim current = CType(_bsOrderDetails.Current, OrderDetail)
    		current.Quantity = 9 ' being lazing to edit in the DataGridView
    		_bsOrderDetails.ResetBindings(False)
    	End Sub
    	''' <summary>
    	''' Revert current to original
    	''' </summary>
    	''' <param name="sender"></param>
    	''' <param name="e"></param>
    	Private Sub button1_Click(ByVal sender As Object, ByVal e As EventArgs)
    		_northWindEntities.Entry(CType(_bsOrderDetails.Current, OrderDetail)).Reload()
    	End Sub
    	Public Sub RollBack()
    		Dim context = _northWindEntities
    		Dim changedEntries = context.ChangeTracker.Entries().Where(Function(x) x.State <> EntityState.Unchanged).ToList()
    
    		For Each entry In changedEntries
    			Select Case entry.State
    				Case EntityState.Modified
    					entry.CurrentValues.SetValues(entry.OriginalValues)
    					entry.State = EntityState.Unchanged
    				Case EntityState.Added
    					entry.State = EntityState.Detached
    				Case EntityState.Deleted
    					entry.State = EntityState.Unchanged
    			End Select
    		Next entry
    	End Sub
    
    	Private Sub button4_Click(ByVal sender As Object, ByVal e As EventArgs)
    		RollBack()
    	End Sub
    End Class


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites


    I've noticed that you are using tolist for the query that fill your datasource. i'm using local.tobindinglist. My idea that as described in my Problem 2 , is that to detect in any way that if a child entities is loaded from database , to use from local , otherwise to query the database.as I can see your are querying everytime the database. 
    Never had a need to use  local.tobindinglist and have build plenty of apps with Entity Framework. Matter of fact never seen anyone else use this until you today.

    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    Thursday, December 6, 2018 4:58 PM
    Moderator
  • Okay, I off to a four hour coding session and have tried Local.ToBindingList, works for me. No time to convert to VB.NET.

    public List<OrderDetail> GetOrders(int pIdentifier) 
    {
        _northWindEntities.OrderDetails.Load();
        return _northWindEntities.OrderDetails
            .Local.ToBindingList()
            .Where(item => item.OrderID == pIdentifier).ToList(); ;
    }


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    Thursday, December 6, 2018 5:10 PM
    Moderator
  • Okay, I off to a four hour coding session and have tried Local.ToBindingList, works for me. No time to convert to VB.NET.

    public List<OrderDetail> GetOrders(int pIdentifier) 
    {
        _northWindEntities.OrderDetails.Load();
        return _northWindEntities.OrderDetails
            .Local.ToBindingList()
            .Where(item => item.OrderID == pIdentifier).ToList(); ;
    }


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites


    you are not working with bindinglist , because after calling tobindinglist you have continued with where and at the end you have finished with Tolist , so at the end you have a list.
    Thursday, December 6, 2018 6:17 PM