Solved

LINQ to SQL 1:N relationship problem

Posted on 2008-06-14
2
1,258 Views
Last Modified: 2008-06-25
Hello,

suppose I have these two tables in SQL Server 2005:

Authors:
ID - int, IDENTITY, autoincremented, autogenerated integer
Name - nvarchar(50)

Books:
ID - int, IDENTITY, autoincremented, autogenerated integer
Title - nvarchar(50)
AuthorID - int, foreign key to Authors. Cannot be null.

Let's suppose the relation is really 1:N so that each book has exactly one author. Now I want to connect by LINQ to SQL and create a new entry in both tables. So I do this:

    [Table(Name = "dbo.Authors")]
    class Author
    {
        [Column(IsPrimaryKey = true, AutoSync = AutoSync.OnInsert, IsDbGenerated = true, DbType = "Int IDENTITY")]
        public int ID { get; set; }

        [Column]
        public string Name { get; set; }
    }

    [Table(Name = "dbo.Books")]
    class Book
    {
        [Column(IsPrimaryKey = true, AutoSync = AutoSync.OnInsert, IsDbGenerated = true, DbType = "Int IDENTITY")]
        public int ID { get; set; }
        public string Title { get; set; }

        // This is how we get linked to the related Author record
        // See http://msdn.microsoft.com/en-us/library/bb386950.aspx
        public int AuthorID { get; set; }
        private EntityRef<Author> _Author;
        [Association(Storage = "_Author", ThisKey = "AuthorID")]
        public Author Author
        {
            get { return this._Author.Entity; }
            set { this._Author.Entity = value; }
        }
    }

and I add a new book with a code like this where Author already exists and has a valid ID:
        private static Book AddBook(DataContext context, Author author)
        {
            // Get the table object
            Table<Book> table = context.GetTable<Book>();

            // Create a new instance of Book
            Book ts = new Book();
            ts.Name = "Something";
            ts.Author = author;

            // Insert to the db
            table.InsertOnSubmit(ts);
            // Submit the changes
            context.SubmitChanges();

            return ts;
        }

The problem is that I context.SubmitChanges fails with the exception that it cannot add a record whose AuthorID is NULL. And I don't have any clue why. I tried to change the set Author method in Book to
            set { AuthorID = value.ID; this._Author.Entity = value; }
so that the AuthorID gets the correct value but this did not help.
I got the original code from http://msdn.microsoft.com/en-us/library/bb386950.aspx

I'm doing it in VC#2008 Express, SQL Server 2005 Express, WinXP Professional SP2 Czech, .NET 3.5.

Can you help me, please?

Thanks

Bolek
0
Comment
Question by:bovlk
2 Comments
 
LVL 13

Assisted Solution

by:joechina
joechina earned 250 total points
ID: 21794093
Try load the author , then load the books of the author, then add a book.
For example

var author = dc.Authors.Single(a => a.AuthId == 1);
author.Books.Load();  //this is required when lazy load is on (delay load is true)
Book b = new Book();
b.Name = "Test Book";
author.Books.Add(b);
dc.SubmitChanges();


0
 

Accepted Solution

by:
bovlk earned 0 total points
ID: 21804098
Thanks joechina. Meanwhile, I found the error in my code. The [Column] attribute is missing on AuthorID in class Book. Should be:

[Column]
public int AuthorID { get; set; }
0

Featured Post

Comprehensive Backup Solutions for Microsoft

Acronis protects the complete Microsoft technology stack: Windows Server, Windows PC, laptop and Surface data; Microsoft business applications; Microsoft Hyper-V; Azure VMs; Microsoft Windows Server 2016; Microsoft Exchange 2016 and SQL Server 2016.

Join & Write a Comment

Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
Slowly Changing Dimension Transformation component in data task flow is very useful for us to manage and control how data changes in SSIS.
Via a live example combined with referencing Books Online, show some of the information that can be extracted from the Catalog Views in SQL Server.
Via a live example, show how to backup a database, simulate a failure backup the tail of the database transaction log and perform the restore.

705 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now