Linq to Sql Foreign key relationships

2019-07-11 11:49发布

问题:

Table name: Author

  • AuthorID -> primary key
  • FirstName
  • LastName

Table name: Titles

  • ISBN -> primary key
  • BookTitle
  • EditionNumber
  • CopyRight

Table name: AuthorISBN

  • ISBN -> foreign key
  • AuthorID -> foreign key

How come the below code block below does not trigger the intellisense, since Linq-to-SQL automatically creates properties based on foreign-key relationship? In my case it doesn't...

ERROR:

The name title does not exist in current context in title.AuthorISBN

It's not letting me add a photo, but 'Author' has 'one-to-many' relationship with AuthorISBN, and 'Titles' also has 'one-to-many' relationship with AuthorISBN

Code:

 BooksDataContext database = new BooksDataContext();
 var authorsAndTitles =
          from title in database.Titles
          from book in title.AuthorISBN
          let author = book.Author
          orderby author.LastName, aurthor.FirstName, title.BookTitle
          select new { author.FirstName, author.LastName, title.BookTitle };

回答1:

It seems like you made a typo:

 var authorsAndTitles =
          from title in database.Titles
          from book in **tilte**.AuthorISBN
          let author = book.Author
          orderby author.LastName, aurthor.FirstName, title.BookTitle
          select new { author.FirstName, author.LastName, title.BookTitle };

Shouldn't it be title.AuthorISBN insteand of tilte.AuthorISBN? I surrounded the word with **.

Besides that, I would try this:

var authorsAndTitles =
          from title in database.Titles
          let author = title.AuthorISBN.Author
          orderby author.LastName, aurthor.FirstName, title.BookTitle
          select new { author.FirstName, author.LastName, title.BookTitle };

New attempt:

var authorsAndTitles =
          from autISBN in database.AuthorISBN
          let author = autISBN.Author
          let title = autISBN.Titles
          orderby author.LastName, author.FirstName, title.BookTitle
          select new { author.FirstName, author.LastName, title.BookTitle };