May 21, 2010

Entity Framework 4 : Cascaded Delete in Parent-Child Relationship?

Extending the previous post, let’s look at cascaded delete

image

[TestMethod]

[ExpectedException(typeof(System.Data.ObjectNotFoundException))]

public void DeleteParentEntity_WithOneToOneChildEntityRelationshipConstraint_ChildIsAutomaticallyDeleted()

{

    // save parent and child (1:1)

    FinanceMinister financeMinister = new FinanceMinister

    {

        Name = "Giulio Tremonti",

        Email = "gt@finanze.it"

    };

    Country country = new Country

    {

        Name = "Italy",

        GDP = 2118.264M, // billions ?

        ForeignDebt = 0M,

        FinanceMinister = financeMinister

    };

    this.target.Add(country);

    this.target.Save();

    int financeMinisterId = financeMinister.Id;

 

    // check if that was done right

    Country reloadedCountry = this.target.GetById<Country>(new Country { Id = country.Id });

    Assert.AreEqual<string>(country.FinanceMinister.Name, reloadedCountry.FinanceMinister.Name);

 

    // delete Country and check that treasurer is also gone

    this.target.Delete(country);

    this.target.Save();

    this.target.GetById<FinanceMinister>(new FinanceMinister { Id = financeMinisterId });

}

throws

image

Now setting the relationship to “cascade”

image

Runs OK, deleting the country and the corresponding finance minister in one go:

image

image

No comments:

Post a Comment