Solved

LINQ to SQL 1:N relationship problem

Posted on 2008-06-14
2
1,259 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

Optimizing Cloud Backup for Low Bandwidth

With cloud storage prices going down a growing number of SMBs start to use it for backup storage. Unfortunately, business data volume rarely fits the average Internet speed. This article provides an overview of main Internet speed challenges and reveals backup best practices.

Question has a verified solution.

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

Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
Ever wondered why sometimes your SQL Server is slow or unresponsive with connections spiking up but by the time you go in, all is well? The following article will show you how to install and configure a SQL job that will send you email alerts includ…
Viewers will learn how the fundamental information of how to create a table.
Viewers will learn how to use the SELECT statement in SQL and will be exposed to the many uses the SELECT statement has.

919 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

21 Experts available now in Live!

Get 1:1 Help Now