LINQ to SQL Insert Associations Example

Adding associated / related entities with LINQ to SQL is a breeze. In the snippet below we add a new TaskList with a new Task (‘Refactor’) for a specific Employee. LINQ to SQL keeps track of the associations and adds them as expected. Note there is no direct attachement needed for the TaskList object to the datacontext. It’s added to the database using some LINQ to SQL magic ;-).

using System;
using System.Linq;
using Remondo.Database;
 
namespace LinqToSqlAssociations
{
    internal class Program
    {
        private static void Main()
        {
            using (var dataContext =
                new RemondoDataContext {Log = Console.Out})
            {
                Employee employee =
                    dataContext.Employees
                        .First(e => e.Name.StartsWith("Leon"));
 
                var task = new Task {Name = "Refactor"};
 
                new TaskList
                    {
                        Employee = employee,
                        Task = task,
                    };
 
                dataContext.SubmitChanges();
 
                Console.ReadKey();
            }
        }
    }
}

LINQ To SQL Associations Console

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>