Click here to Skip to main content
15,880,956 members
Articles / Desktop Programming / WPF

A LINQ Tutorial: WPF Data Binding with LINQ to SQL

Rate me:
Please Sign up or sign in to vote.
4.90/5 (47 votes)
11 Dec 2009CPOL9 min read 186.6K   9.3K   99  
A tutorial and application on using WPF Data Binding with LINQ to SQL classes. This is part 3 of a three-part tutorial on using LINQ to SQL.
/*********************************************************************
 * A LINQ Tutorial: WPF Data Binding with LINQ to SQL
 * By: Abby Fichtner, http://www.TheHackerChickBlog.com
 * Article URL: http://www.codeproject.com/KB/linq/linqtutorial3.aspx
 * Licensed under The Code Project Open License (CPOL)
 *********************************************************************/

using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.Linq;
using LINQDemo.View;

namespace LINQDemo
{
#pragma warning disable 0169        // disable never used warnings for fields that are being used by LINQ

    [Table( Name = "Authors" )]
    public class Author : IBookCollection, INotifyPropertyChanged
    {
        [Column( IsPrimaryKey = true, IsDbGenerated = true )]
        public int Id { get; set; }

        private string _name;
        [Column] public string Name {
            get { return _name; }
            set {
                _name = value;
                OnPropertyChanged( "Name" );
            }
        }

        private EntitySet<BookAuthor> _bookAuthors = new EntitySet<BookAuthor>( );
        [Association( Name = "FK_BookAuthors_Authors", Storage = "_bookAuthors", OtherKey = "authorId", ThisKey = "Id" )]
        internal ICollection<BookAuthor> BookAuthors {
            get { return _bookAuthors; }
            set { _bookAuthors.Assign( value ); }
        }

        public ICollection<Book> Books {
            get {
                var books = new ObservableCollection<Book>( from ba in BookAuthors select ba.Book );
                books.CollectionChanged += BookCollectionChanged;
                return books;
            }
        }

        private void BookCollectionChanged( object sender, NotifyCollectionChangedEventArgs e ) {
            if( NotifyCollectionChangedAction.Add == e.Action ) {
                foreach( Book addedBook in e.NewItems )
                    OnBookAdded( addedBook );
            }

            if( NotifyCollectionChangedAction.Remove == e.Action ) {
                foreach( Book removedBook in e.OldItems )
                    OnBookRemoved( removedBook );
            }

            // Call OnPropertyChanged() after updating Books
            OnPropertyChanged( "Books" );
        }

        private void OnBookAdded( Book addedBook ) {
            BookAuthor ba = new BookAuthor( ) { Author = this, Book = addedBook };
        }

        private void OnBookRemoved( Book removedBook ) {
            BookAuthor baRecord = BookAuthors.SingleOrDefault( ba => ba.Author == this && ba.Book == removedBook );
            if( baRecord != null ) {
                baRecord.Remove( );
            }
        }

        public bool CanDelete( ) {
            // don't allow delete if there are books by this author
            return Books.Count == 0;
        }
        
        public event PropertyChangedEventHandler PropertyChanged;
        private void OnPropertyChanged( string name ) {
            if( PropertyChanged != null ) {
                PropertyChanged( this, new PropertyChangedEventArgs( name ) );
            }
        }
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer Microsoft
United States United States
Abby Fichtner is a Microsoft Developer Evangelist and author of The Hacker Chick Blog.

She's been developing custom software applications, wearing every hat imaginable, since 1994. Although, technically, she got her start at the age of 8 when her father brought home an Atari 800. In the evenings, they would sit together and type in the machine code from the Atari magazines – because that was the way serious geeks got their computer games!

Today, she works for Microsoft as a Developer Evangelist to the startup community - helping them to create the next generation of software.

Comments and Discussions