Foreign key relationships in Entity Framework

Posted by Anders Svensson on Stack Overflow See other posts from Stack Overflow or by Anders Svensson
Published on 2010-05-24T10:38:42Z Indexed on 2010/05/24 10:41 UTC
Read the original article Hit count: 240

Filed under:

I'm trying to add an object created from Entity Data Model classes. I have a table called Users, which has turned into a User EDM class. And I also have a table Pages, which has become a Page EDM class. These tables have a foreign key relationship, so that each page is associated with many users. Now I want to be able to add a page, but I can't get how to do it. I get a nullreference exception on Users below. I'm still rather confused by all this, so I'm sure it's a simple error, but I just can't see how to do it.

Also, by the way, the compiler requires that I set PageID in the object initializer, even though this field is set to be an automatic id in the table. Am I doing it right just setting it to 0, expecting it to be updated automatically in the table when saved, or how should I do that?

Any help appreciated!

The method in question:

        private Page GetPage(User currentUser)
    {
        string url = _request.ServerVariables["url"].ToLower();
        var userPages = from p in _context.PageSet
                           where p.Users.UserID == currentUser.UserID
                           select p;
        var existingPage = userPages.FirstOrDefault(e => e.Url == url); //Could be combined with above, but hard to read?

        if (existingPage != null)
            return existingPage;
        Page page = new Page()
                        {
                            Count = 0,
                            Url = _request.ServerVariables["url"].ToLower(),
                            PageID = 0, //Only initial value, changed later?                                
                        };

        _context.AddToPageSet(page);
        page.Users.UserID = currentUser.UserID; //Here's the problem...
        return page;
    }

© Stack Overflow or respective owner

Related posts about entity-framework