Using the "previous” example the code to insert records would be:
Linq to SQL
LTSModelDataContext lts = new LTSModelDataContext();
Person person = new Person()
{
FirstName = "Juan",
LastName = "Perez",
MiddleName = "LTS", //Linq to SQL
};
lts.Persons.InsertOnSubmit(person);
lts.SubmitChanges();
Linq to Entities
LTEEntities lte = new LTEEntities();
Persons person = new Persons()
{
FirstName = "Juan",
LastName = "Perez",
MiddleName = "LTE", //Linq to Entities
};
lte.AddToPersons(person);
lte.SaveChanges();
Nothing to complicated.
If we want to insert contact information for a person, based on our model, we need to insert a record on the ContactInfos table, and then link the ContactInfo key with the Person key on the PersonContactInfos table.
Link to Entities is actually very simple, since the Model created from the DB only has two classes, we just need to create a ContactInfos object use the AddToContactInfos() method on our entity model, add it to the list of our Person object and save changes.
The code looks like this:
LTEEntities lte = new LTEEntities();
Persons person = new Persons()
{
FirstName = "Juan",
LastName = "Perez",
MiddleName = "LTE", //Linq to Entities
};
ContactInfos contactInfo = new ContactInfos()
{
ContactInfo = "15 Yemen Road, Yemen",
ContactType = 0 // Assuming 0 is Address
};
person.ContactInfos.Add(contactInfo);
lte.AddToPersons(person);
lte.SaveChanges();
Link to SQL needs an extra step, linking ContactInfo to the Person is done “manually”, the code looks like this:
LTSModelDataContext lts = new LTSModelDataContext();
Person person = new Person()
{
FirstName = "Juan",
LastName = "Perez",
MiddleName = "LTS", //Linq to SQL
};
ContactInfo contactInfo = new ContactInfo()
{
ContactInfo1 = "15 Yemen Road, Yemen",
ContactType = 0 // Assuming 0 is Address
};
PersonContactInfo personContactInfo = new PersonContactInfo()
{
ContactInfo = contactInfo,
Person = person
};
lts.Persons.InsertOnSubmit(person);
lts.SubmitChanges();
Please note that since we are using many to many, it shouldn’t matter if we add the person to the contactInfo or the other way around.
Also, is not necessary to add all the objects to their add methods (or SubmitOnInsert methods) the model “figures” what needs to be added and gets added.
Also, remember this is only inserting new objects, edit and delete will come soon.