LINQ provides an easy way to save the master-child data and you need not worry about the PK/FK relations or manage them manually. Let us see how to save the Country/City information using LINQ

Create an instance of the DataContext you are working on. DataContext will be created when you create a new Linq To Sql file (.dbml). Drag the tables Country and City onto the designer and the relation will be created automatically. You can also see the filed names of the corresponding tables shown as properties the classes.

[code:c#]
ExampleDataContext db = new ExampleDataContext();
[/code]


Create the new Country and City

[code:c#]

// create a new country
Country country = new Country();
country.Name = "myCountry";

// create the cities
City city1 = new City();
city1.Name = "myCity1";

City city2 = new City();
city2.Name = "myCity2";

// relate the cities with the new country created
// because of the PK/FK relation, you will find the cities collection as a property of the Country which is automatically created by LINQ for you
country.Cities.Add(city1);
country.Cities.Add(city2);

// add the country to the database and save the changes
db.Countries.Add(country);
db.SubmitChanges();
[/code]


E Screw