Posts

....
Technical Blog for .NET Developers ©

Sunday, September 14, 2014

Entity Framework Change Tracker

With ChangeTracker we can track the state of the entities in the database context, so when our processes work into a context we can work on specific group of entities

In this example we have this diagram and a class which handles the retrieve and insert methods. This is the implementation:



 
        public IEnumerable<GALAXIES> GetKnownGalaxies()
        {
            return (from GALAXIES galaxies in _context.GALAXIES select galaxies);
        }

        public void InsertGalaxy(GALAXIES galaxy)
        {
            _context.GALAXIES.Attach(galaxy);
            _context.Entry(galaxy).State = EntityState.Added;
            _context.GALAXIES.Add(galaxy);
        }
       


Now we add a third method to retrieve only the added galaxies:

     
        public IEnumerable<GALAXIES> GetNewGalaxies()
        {
            return
                (from GALAXIES galaxies in _context.ChangeTracker.Entries()
                     .Where(e => e is GALAXIES && e.State == EntityState.Added)
                     .Select(e => e.Entity as GALAXIES)
                 select galaxies);
        }

        public void InsertNewGalaxy()
        {
            GALAXIES newGalaxy = new GALAXIES()
                {
                    Name = "Cartwheel Galaxy",
                    Distance = (decimal)1.5,
                    Magnitude = (decimal)2.9
                };

            galaxyClass.InsertGalaxy(newGalaxy);
        }
    


The result of the program with this sequence is the next:

     
        var knownGalaxies = galaxyClass.GetKnownGalaxies().ToList();

        knownGalaxies.ForEach(
            x =>
            Console.WriteLine("{0}: {1} distance, {2} magnitude", 
                                x.Name, x.Distance.ToString(),
                                x.Magnitude.ToString()));

        Console.WriteLine(Environment.NewLine);
        Console.ReadKey();

        InsertNewGalaxy();

        var newGalaxies = galaxyClass.GetNewGalaxies().ToList();

        newGalaxies.ForEach(
            x =>
            Console.WriteLine("{0}: {1} distance, {2} magnitude", 
                                x.Name, x.Distance.ToString(),
                                x.Magnitude.ToString()));
    





<METHOD SOFTWARE © 2014>