Solved

LINQ to SQL 1:N relationship problem

Posted on 2008-06-14
2
1,267 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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

Efficient way to get backups off site to Azure

This user guide provides instructions on how to deploy and configure both a StoneFly Scale Out NAS Enterprise Cloud Drive virtual machine and Veeam Cloud Connect in the Microsoft Azure Cloud.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Ever needed a SQL 2008 Database replicated/mirrored/log shipped on another server but you can't take the downtime inflicted by initial snapshot or disconnect while T-logs are restored or mirror applied? You can use SQL Server Initialize from Backup…
The Delta outage: 650 cancelled flights, more than 1200 delayed flights, thousands of frustrated customers, tens of millions of dollars in damages – plus untold reputational damage to one of the world’s most trusted airlines. All due to a catastroph…
Using examples as well as descriptions, and references to Books Online, show the different Recovery Models available in SQL Server and explain, as well as show how full, differential and transaction log backups are performed
This videos aims to give the viewer a basic demonstration of how a user can query current session information by using the SYS_CONTEXT function

688 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