Entity Framework – Lazy Loading, Direct Loading, Eagerly Loading

Every time we get an entity from EF the related entities are not automatically loaded. They will be loaded at the first attempt to access, so that from user’s point of view anything changes. This mechanism is called Lazy loading. Here is a little example:

Person person;
using (var cont = new TestDBEntities())
{
    person = cont.Persons.First(p => p.IdPerson == 1);
 
    var cityName = person.City.CityName;
    var genderName = person.Gender.GenderName;
    var carDescription = person.Cars.First().CarDescription;
}

This code works with no problems. The related entities City, Gender and Cars are automatically downloaded at first access, so we can read their fields without realizing that the Lazy Loading is working behind the scenes. We can instead realize it with the following change:

Person person;
using (var cont = new TestDBEntities())
{
    person = cont.Persons.First(p => p.IdPerson == 1);
}
 
var cityName = person.City.CityName;
var genderName = person.Gender.GenderName;
var carDescription = person.Cars.First().CarDescription;

In this case we can see the Lazy Loading at works, because at the first attempt to access a related entity we’ll get an exception telling that: “The ObjectContext instance has been disposed and can no longer be used for operations that require a connection”.

What does it means? It means that when we first try to access to read a property, the Lazy Loading attempt to load the related entity from the database, failing because the EF context has been disposed. If we look at the related entities in this moment they are all = null. This is a situation that we can easily have if we work with MVC Framework, where we could have some code like this within our controller:

public ActionResult MyAction()
{
    using (var cont = new TestDBEntities())
    {
        return View(cont.Persons.First(p => p.IdPerson == 1));
    }
}

If we try to access a related entity from the Razor view related with this action we’ll get the same error. This because when the Razor view is processed the controller’s action has already returned and our EF context has already been disposed.

So how can we do if we are in this situation? There are many solution, the simplest one it to explicitly pre-load all the related entities. This mechanism is called Explicit Loading and works taking advantage on the EF cache, where all the entities loaded from previous queries are stored to be reused. EF only uses the Lazy Loading for related entities not yet in the cache. Those which are already present will be automatically assigned without needing any extra access to the DB. Here is an example:

Person person;
using (var cont = new TestDBEntities())
{
    person = cont.Persons.First(p => p.IdPerson == 1);
    cont.Cities.Where(c => c.IdCity == person.IdCity).Load();
    cont.Genders.Where(g => g.IdGender == person.IdGender).Load();
    cont.Cars.Where(c => c.IdPerson == person.IdPerson).Load();
}
 
var cityName = person.City.CityName;
var genderName = person.Gender.GenderName;
var carDescription = person.Cars.First().CarDescription;

If we try to run this example we’ll see that the City and the Gender are loaded, while the related Cars are still not present. That’s because the Explicit Loading only works with related entities on the N-side of a 1:N relationship. The Cars are on the 1-side of a 1:N relationship, so EF can’t be sure that the pre-loaded Cars in its cache are all the cars needed, so it leave the reference = null. To have the Cars loaded as well we need to change our code in this way:

Person person;
using (var cont = new TestDBEntities())
{
    person = cont.Persons.First(p => p.IdPerson == 1);
    cont.Cities.Where(c => c.IdCity == person.IdCity).Load();
    cont.Genders.Where(g => g.IdGender == person.IdGender).Load();
    cont.Entry(person).Collection(p => p.Cars).Load();
}
 
var cityName = person.City.CityName;
var genderName = person.Gender.GenderName;
var carDescription = person.Cars.First().CarDescription;

Another approach is to ask EF to directly include the related entities we are interested in while is loading our person. This mechanism is called Eagerly Loading and is probably the most clean we can use:

Person person;
using (var cont = new TestDBEntities())
{
    person = cont.Persons.Include(p => p.City)
        .Include(p => p.Gender).Include(p => p.Cars).First(p => p.IdPerson == 1);
}
 
var cityName = person.City.CityName;
var genderName = person.Gender.GenderName;
var carDescription = person.Cars.First().CarDescription;
Advertisements

Jasmine JS, Angular JS – Testing of an Angular Directive

We need Chutzpah to be able to run this test. Resharper has some problem when loading the directive’s template.

http://blogs.msdn.com/b/matt-harrington/archive/2014/10/27/javascript-unit-testing-using-the-chutzpah-test-runner-in-visual-studio.aspx

With the Chuzpah extensions for VS (Test Runner and Test Adapter) we can see the JS tests within the default Visual Studio Text Explorer and run them from there, in the same way we manage the standard C# tests.

Here is our test:

//References of all the .JS needed for the test
/// <reference path="../../../scripts/jquery-2.1.3.min.js" />
/// <reference path="../../../scripts/jasmine.js" />
/// <reference path="../../../scripts/angular.min.js" />
/// <reference path="../../../scripts/angular-mocks.js" />
/// <reference path="../../app/app.js" />
/// <reference path="../../app/directives/d.personsList.js" />

describe("Directive Persons List:", function () {
    describe("When the directive is compiled", function () {
        var $scope, target;
 
        beforeEach(function () {
 
            //Load the module to test
            module("app.directives");
 
            //The inject() function is used to resolve dependencies.
            //I can then assign the dependencies that I receive here to variables
            //defined outside the function. Is possible as well to use "_" to refer
            //a dependency without overriding the related outer reference.
            //For instance i could refer the $rootScope dependency with the name
            //"_$rootScope_", to assign it to an outer reference named "$rootScope"
            inject(function ($rootScope, $templateCache, $compile) {
 
                //Create the test $scope
                $scope = $rootScope.$new();
                $scope.persons = [
                    { name: "name1", surname: "surname1" },
                    { name: "name2", surname: "surname2" },
                    { name: "name3", surname: "surname3" }
                ];
 
                //Push the directive's template on the
                //template cache (work only with Chutzpah)
                var view = $templateCache.get("/jsApp/app/directives/d.personsList.html");
                if (!view) {
                    $.ajax({
                        type: "GET",
                        async: false,
                        cache: false,
                        url: "../../app/directives/d.personsList.html"
                    })
                    .done(function (data) {
                        view = data;
                    });
                    $templateCache.put("/jsApp/app/directives/d.personsList.html", view);
                }
 
                //Compile the directive using the test $scope
                target = $compile("<persons-list persons='persons'></persons-list>")($scope);
                $scope.$digest();
            });
        });
 
        it("It should be defined", function () {
            expect(target).toBeDefined();
        });
 
        it("It should contain a person list", function () {
            var personList = target.find("li");
            expect(personList.length).toBe(3);
            for (var n = 0; n < 3; n++) {
                expect($(personList[n]).text().trim()).toBe(
                    $scope.persons[n].name + " " + $scope.persons[n].surname);
            }
        });
    });
});

Here is our directive’s code

angular.module("app.directives").directive("personsList", function () {
    return {
        restrint: "E",
        replace: true,
        templateUrl: "/jsApp/app/directives/d.personsList.html",
        scope: {
            persons: "="
        }
    };
});

Here is our directive’s template

<ul>
    <li ng-repeat="person in persons">
        {{person.name}} {{person.surname}}
    </li>
</ul>

SOLID Principles

S: Single Responsibility Principle

A class should have a single and specific role. For instance, a Customer class should validate the customer’s data, interact with the underlying data layer etc.. Should not do logging activity. If we need the logging within a Customer class we should delegate this to an inner Logger class instance, which has the logging responsibility. This ensure us that if there’s something to change on some responsibility’s logic, we have to change only one class.

O: Open Closed Principle

A class should be Open to extensions, but closed to changes. For instance if we have different types of customers we should not represent this with a Type property within our Customer class, because in this way we are forced to change the class every time we need a new type. By respecting this principle we should represent every customer different type with a proper subclass of Customer.

L: Liskov Substitution Principle

If q(x) is a property that is valid for all x of type T, then q(y) should be valid as well for all y of type S, where S is a subclass of T.

This means that if a subclass of our Customer class don’t implement some of the Customer properties, we should remove the direct inheritance between them and use instead two interfaces to separate the properties that are valid for both the Customer class and the subclass (so that both of them can implement it) from the properties that are valid for the Customer class only (so that only the Customer class can implement it). In this way we can’t use the polymorphism to assign to a Customer reference an instance of a subclass that don’t implement some of the Customer’s properties.

I: Interface Segregation Principle

This principle says that we should have many little and specific interfaces (one for every behavior of our class clients) instead of having a single and big generic interface. This ensures that our class clients don’t depend on properties that they don’t use. For instance if some of our class clients use just a specific subset of properties, while another part of them uses all of them, we should have one interface for the first ones, with just the properties they use, and another one for the clients who use all of the properties. In this way the clients that don’t use all the properties don’t see the properties that they don’t use.

D: Dependency Inversion Principle

This principle says that is not a responsibility for a class to create (deciding their type) its dependencies. They should be injected from outside. From this principle came the IoC principle.

Comparing XML with XMLDiff

https://msdn.microsoft.com/en-us/library/aa302295.aspx

var xmldiff = new XmlDiff(
    XmlDiffOptions.IgnoreChildOrder | XmlDiffOptions.IgnoreNamespaces
    | XmlDiffOptions.IgnorePrefixes | XmlDiffOptions.IgnoreWhitespace);
 
var newXml = new XmlDocument(); newXml.LoadXml(newDoc.ToString());
var newNode = newXml.SelectSingleNode("myNode");
 
var prevXml = new XmlDocument(); prevXml.LoadXml(prevDoc.ToString());
var prevNode = prevXml.SelectSingleNode("myNode");
 
var stringWriter = new StringWriter();
var xmlWriter = new XmlTextWriter(stringWriter);
if (!xmldiff.Compare(prevNode, newNode, xmlWriter))
{
    //Get the differences
    var diffXml = new XmlDocument();
    diffXml.LoadXml(stringWriter.ToString());
    ...
}

Read/Write from a FTP source

Reading

using (var ftpClient = new WebClient
{
    Credentials = new NetworkCredential(_config.Upload_FtpUsername, _config.Upload_FtpPassword),
    Encoding = Encoding.UTF8
})
{
    Notify(this, new Message(string.Format("Attempting to Write {0} to the FTP Server", request)));
    var content = File.ReadAllText(request.SourceFilePath);
 
    //Upload the request
    ftpClient.UploadString(request.DestFilePath, content);
}

Writing

using (var ftpClient = new WebClient
{
    Credentials = new NetworkCredential(_config.Upload_FtpUsername, _config.Upload_FtpPassword)
})
{
    Notify(this, new Message("Attempting to Read from the FTP Server"));
    var ftpAddress = _config.TargetServer + @"/" + _config.TargetFilepath
        + @"/" + targetFolder + @"/" + targetSubFolder + @"/" + _config.TargetFilename;
 
    //Download the feed
    var readStr = ftpClient.DownloadString(ftpAddress);
    var newDoc = XDocument.Parse(readStr);
    return newDoc;
}

Entity Framework Repositories (Part 2)

This example tries to achieve the same result as the previous post, but with the cooperation of many dedicated repositories (one for each entity), in order to distribute the complexity.

The Car Repository (no dependencies)

public class CarRepository : IRepository<Car, int>
{
    private readonly DbContext _context;
 
    public CarRepository(DbContext context)
    {
        _context = context;
    }
 
    public IEnumerable<Car> GetAll()
    {
        return _context.Set<Car>().ToList();
    }
 
    public Car GetById(int id)
    {
        return _context.Set<Car>().Find(id);
    }
 
    public Car AddNew(Car entity, bool saveChanges = true)
    {
        return AddUpdate(entity, saveChanges);
    }
 
    public Car Update(Car entity, bool saveChanges = true)
    {
        return AddUpdate(entity, saveChanges);
    }
 
    public void Delete(int id, bool saveChanges = true)
    {
        var car = GetById(id);
        _context.Set<Car>().Remove(car);
        if (saveChanges)
            _context.SaveChanges();
    }
 
    public void SaveChanges()
    {
        _context.SaveChanges();
    }
 
    private Car AddUpdate(Car entity, bool saveChanges)
    {
        Car car;
        if (entity.IdCar == 0)
        {
            car = _context.Set<Car>().Create();
            _context.Set<Car>().Add(car);
        }
        else
            car = GetById(entity.IdCar);
        _context.Entry(car).CurrentValues.SetValues(entity);
        if (saveChanges)
            _context.SaveChanges();
        return car;
    }
}

The Person Repository (Car as dependency)

public class PersonRepository : IRepository<Person, int>
{
    private readonly DbContext _context;
    private readonly IRepository<Car, int> _carRepository;
 
    public PersonRepository(DbContext context,
        IRepository<Car, int> carRepository)
    {
        _context = context;
        _carRepository = carRepository;
    }
 
    public IEnumerable<Person> GetAll()
    {
        return _context.Set<Person>().ToList();
    }
 
    public Person GetById(int id)
    {
        return _context.Set<Person>().Find(id);
    }
 
    public Person AddNew(Person entity, bool saveChanges = true)
    {
        return AddUpdate(entity, saveChanges);
    }
 
    public Person Update(Person entity, bool saveChanges = true)
    {
        return AddUpdate(entity, saveChanges);
    }
 
    public void Delete(int id, bool saveChanges = true)
    {
        var person = GetById(id);
 
        //Delete dependencies before deleting
        person.Cars.ToList().ForEach(car =>
            _carRepository.Delete(car.IdCar, false));
        _context.Set<Person>().Remove(person);
        if (saveChanges)
            _context.SaveChanges();
    }
 
    public void SaveChanges()
    {
        _context.SaveChanges();
    }
 
    private Person AddUpdate(Person entity, bool saveChanges)
    {
        Person person;
        if (entity.IdCity == 0)
        {
            person = _context.Set<Person>().Create();
            _context.Set<Person>().Add(person);
        }
        else
            person = GetById(entity.IdPerson);
        _context.Entry(person).CurrentValues.SetValues(entity);
 
        //Delete dependencies before updating
        person.Cars.Where(car => entity.Cars.All(entityCar =>
            entityCar.IdCar != car.IdCar)).ToList().ForEach(car =>
                _carRepository.Delete(car.IdCar, false));
 
        //Add/Update dependecies before updating
        entity.Cars.ToList().ForEach(entityCar =>
        {
            //Ensures that the FK is set
            entityCar.IdPerson = entity.IdPerson;
            if (entityCar.IdCar == 0)
                person.Cars.Add(_carRepository.AddNew(entityCar, false));
            else
                _carRepository.Update(entityCar, false);
        });
        if (saveChanges)
            _context.SaveChanges();
        return person;
    }
}

The City Repository (Person as Dependency)

public class CityRepository2 : IRepository<City, int>
{
    private readonly DbContext _context;
    private readonly IRepository<Person, int> _personRepository;
 
    public CityRepository2(DbContext context,
        IRepository<Person, int> personRepository)
    {
        _context = context;
        _personRepository = personRepository;
    }
 
    public IEnumerable<City> GetAll()
    {
        return _context.Set<City>().ToList();
    }
 
    public City GetById(int id)
    {
        return _context.Set<City>().Find(id);
    }
 
    public City AddNew(City entity, bool saveChanges = true)
    {
        return AddUpdate(entity, saveChanges);
    }
 
    public City Update(City entity, bool saveChanges = true)
    {
        return AddUpdate(entity, saveChanges);
    }
 
    public void Delete(int id, bool saveChanges = true)
    {
        var city = GetById(id);
 
        //Delete dependencies before deleting
        city.Persons.ToList().ForEach(person =>
            _personRepository.Delete(person.IdPerson, false));
        _context.Set<City>().Remove(city);
        if (saveChanges)
            _context.SaveChanges();
    }
 
    public void SaveChanges()
    {
        _context.SaveChanges();
    }
 
    private City AddUpdate(City entity, bool saveChanges)
    {
        City city;
        if (entity.IdCity == 0)
        {
            city = _context.Set<City>().Create();
            _context.Set<City>().Add(city);
        }
        else
            city = GetById(entity.IdCity);
        _context.Entry(city).CurrentValues.SetValues(entity);
 
        //Delete dependencies before updating
        city.Persons.Where(person => entity.Persons.All(entityPerson =>
            entityPerson.IdPerson != person.IdPerson)).ToList().ForEach(person =>
                _personRepository.Delete(person.IdPerson, false));
 
        //Add/Update dependecies before updating
        entity.Persons.ToList().ForEach(entityPerson =>
        {
            //Ensures that the FK is set
            entityPerson.IdCity = entity.IdCity;
            if (entityPerson.IdPerson == 0)
                city.Persons.Add(_personRepository.AddNew(entityPerson, false));
            else
                _personRepository.Update(entityPerson, false);
        });
        if (saveChanges)
            _context.SaveChanges();
        return city;
    }
}

Entity Framework Repositories (Part 1)

Is often useful to use the Repository pattern with EF. Unfortunalely EF doen’t behave as we could expect when interacting for the basic CRUD operations. For example when we delete an entity it doesn’t delete its dependencies on cascade (it try to set their FK to NULL instead, causing DB errors at save time). In addition is difficult to insert/update complex entities (for example an entire object together with its dependencies at the same time), when we don’t just load an entity, change one or two fields, and save it again, like in the 99% of the provided examples. For instance several solutions attempt to directly insert detached POCO entities, without using the Create() method. Doing in this way the insert works, but the entity will not be converted to a EF proxy object and the navigation properties will not be updated. This example tries to show a complete repository that can be easily used on real scenarios. The repository works with City entities on this data structure:

The generic Interface

public interface IRepository<T, in TK>
{
    IEnumerable<T> GetAll();
    T GetById(TK id);
    T AddNew(T entity, bool saveChanges = true);
    T Update(T entity, bool saveChanges = true);
    void Delete(TK id, bool saveChanges = true);
    void SaveChanges();
}

The Implementation

public class CityRepository : IRepository<City, int>
{
    private readonly DbContext _context;
 
    public CityRepository(DbContext context)
    {
        _context = context;
    }
 
    public IEnumerable<City> GetAll()
    {
        return _context.Set<City>().ToList();
    }
 
    public City GetById(int id)
    {
        return _context.Set<City>().Find(id);
    }
 
    public City AddNew(City entity, bool saveChanges = true)
    {
        return AddUpdate(entity, saveChanges);
    }
 
    public City Update(City entity, bool saveChanges = true)
    {
        return AddUpdate(entity, saveChanges);
    }
 
    public void Delete(int id, bool saveChanges = true)
    {
        var city = GetById(id);
 
        //Delete dependencies before deleting
        _context.Set<Car>().RemoveRange(city.Persons
            .SelectMany(person => person.Cars));
        _context.Set<Person>().RemoveRange(city.Persons);
        _context.Set<City>().Remove(city);
        if (saveChanges)
            _context.SaveChanges();
    }
 
    public void SaveChanges()
    {
        _context.SaveChanges();
    }
 
    private City AddUpdate(City entity, bool saveChanges)
    {
        City city;
        if (entity.IdCity == 0)
        {
            city = _context.Set<City>().Create();
            _context.Set<City>().Add(city);
        }
        else
            city = GetById(entity.IdCity);
        _context.Entry(city).CurrentValues.SetValues(entity);
 
        //Delete dependencies before updating
        _context.Set<Car>().RemoveRange(city.Persons
            .SelectMany(person => person.Cars)
            .Where(car => entity.Persons
                .SelectMany(entityPerson => entityPerson.Cars)
                .All(entityCar => entityCar.IdCar != car.IdCar)));
        _context.Set<Person>().RemoveRange(city.Persons
            .Where(person => entity.Persons
                .All(entityPerson =>
                    entityPerson.IdPerson != person.IdPerson)));
 
        //Add/Update dependecies before updating
        entity.Persons.ToList().ForEach(entityPerson =>
        {
            //Ensures that the FK is set
            entityPerson.IdCity = entity.IdCity;
 
            Person person;
            if (entityPerson.IdPerson == 0)
            {
                person = _context.Set<Person>().Create();
                city.Persons.Add(person);
            }
            else
                person = _context.Set<Person>().Find(entityPerson.IdPerson);
            _context.Entry(person).CurrentValues.SetValues(entityPerson);
            entityPerson.Cars.ToList().ForEach(entityCar =>
            {
                //Ensures that the FK is set
                entityCar.IdPerson = entityPerson.IdPerson;
 
                Car car;
                if (entityCar.IdCar == 0)
                {
                    car = _context.Set<Car>().Create();
                    person.Cars.Add(car);
                }
                else
                    car = _context.Set<Car>().Find(entityCar.IdCar);
                _context.Entry(car).CurrentValues.SetValues(entityCar);
            });
        });
        if (saveChanges)
            _context.SaveChanges();
        return city;
    }
}

The Test Class (NUnit)

[TestFixture]
public class When_A_City_Repository_Is_Created
{
    private DbContext _context;
    private DbContextTransaction _transaction;
    private IRepository<City, int> _repository;
 
    [SetUp]
    public void SetUp()
    {
        _context = new TestDBEntities();
        _transaction = _context.Database.BeginTransaction();
        _repository = new CityRepository(_context);
    }
 
    [Test]
    public void It_Should_Get_All_The_Cities()
    {
        var loadedCities = _repository.GetAll();
 
        Assert.IsNotNull(loadedCities);
        Assert.IsTrue(loadedCities.Any());
        Assert.IsTrue(loadedCities.SelectMany(c => c.Persons).Any());
    }
 
    [Test]
    public void It_Should_Get_A_City_By_Id()
    {
        const int id = 1;
        var loadedCity = _repository.GetById(id);
 
        Assert.IsNotNull(loadedCity);
        Assert.AreEqual(loadedCity.IdCity, id);
        Assert.IsTrue(loadedCity.Persons.Any());
    }
 
    [Test]
    public void It_Should_Add_A_New_City()
    {
        var city = new City
        {
            CityName = "TestCity",
        };
        var addedCity = _repository.AddNew(city);
 
        Assert.AreNotEqual(addedCity.IdCity, 0);
        Assert.AreEqual(addedCity.CityName, city.CityName);
    }
 
    [Test]
    public void It_Should_Add_A_New_City_With_Dependencies()
    {
        var city = new City
        {
            CityName = "TestCity",
            Persons = new List<Person>
            {
                new Person
                {
                    Name = "TestPersonName1",
                    Surname = "TestPersonSurname1",
                    IdGender = 1,
                    Cars = new List<Car>
                    {
                        new Car{ CarDescription = "Person1Car1"},
                        new Car{ CarDescription = "Person1Car2"}
                    }
                },
                new Person
                {
                    Name = "TestPersonName2",
                    Surname = "TestPersonSurname2",
                    IdGender = 2,
                    Cars = new List<Car>
                    {
                        new Car{ CarDescription = "Person2Car1"},
                        new Car{ CarDescription = "Person2Car2"}
                    }
                }
            }
        };
        var addedCity = _repository.AddNew(city);
 
        Assert.AreNotEqual(addedCity.IdCity, 0);
        Assert.AreEqual(addedCity.CityName, city.CityName);
        Assert.IsTrue(addedCity.Persons.Count() == 2);
 
        var firstPerson = addedCity.Persons.First();
        Assert.AreNotEqual(firstPerson.IdPerson, 0);
        Assert.AreEqual(firstPerson.IdCity, addedCity.IdCity);
        Assert.AreEqual(firstPerson.Name, "TestPersonName1");
        Assert.IsNotNull(firstPerson.Gender);
        Assert.IsTrue(firstPerson.Cars.Count() == 2);
 
        var firstCar = firstPerson.Cars.First();
        Assert.AreNotEqual(firstCar.IdCar, 0);
        Assert.AreEqual(firstCar.IdPerson, firstPerson.IdPerson);
        Assert.AreEqual(firstCar.CarDescription, "Person1Car1");
    }
 
    [Test]
    public void It_Should_Update_A_City()
    {
        const int id = 1;
        var city = new City
        {
            IdCity = id,
            CityName = "UpdatedCity"
        };
        var uploadedCity = _repository.Update(city);
 
        Assert.AreEqual(uploadedCity.CityName, city.CityName);
    }
 
    [Test]
    public void It_Should_Update_A_City_With_Dependencies()
    {
        const int id = 1;
        var city = new City()
        {
            IdCity = id,
            CityName = "UpdatedCity",
            Persons = new List<Person>
            {
                new Person
                {
                    IdPerson = 2,
                    Name = "UpdatedPersonName",
                    Surname = "UpdatedPersonSurname",
                    IdGender = 2,
                    Cars = new List<Car>
                    {
                        new Car
                        {
                            IdCar = 3,
                            CarDescription = "UpdatedCar"
                        },
                        new Car
                        {
                            CarDescription = "AddedCar"
                        }
                    }
                }
            }
        };
        var uploadedCity = _repository.Update(city);
 
        Assert.AreEqual(uploadedCity.CityName, city.CityName);
        Assert.IsTrue(uploadedCity.Persons.Count() == 1);
 
        var firstPerson = uploadedCity.Persons.First();
        Assert.AreEqual(firstPerson.IdPerson, 2);
        Assert.AreEqual(firstPerson.Name, "UpdatedPersonName");
        Assert.IsTrue(firstPerson.Cars.Count() == 2);
 
        var car1 = firstPerson.Cars.ElementAt(0);
        Assert.AreEqual(car1.IdCar, 3);
        Assert.AreEqual(car1.CarDescription, "UpdatedCar");
        var car2 = firstPerson.Cars.ElementAt(1);
        Assert.AreNotEqual(car2.IdCar, 0);
        Assert.AreEqual(car2.CarDescription, "AddedCar");
    }
 
    [Test]
    public void It_Should_Delete_A_City()
    {
        const int id = 1;
        _repository.Delete(id);
        var loadedCities = _repository.GetAll();
 
        Assert.IsTrue(loadedCities.All(c => c.IdCity != id));
    }
 
    [TearDown]
    public void TearDown()
    {
        _transaction.Rollback();
        _transaction.Dispose();
        _context.Dispose();
    }
}