开发者

Foreign key relationships in Entity Framework

开发者 https://www.devze.com 2022-12-31 04:42 出处:网络
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 cla

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);

   if (existingPage != null)
      return existingPage;

   Page page = new Page()
                   {
                      Count = 0,
                      Url = _request.ServerVariables["url"].ToLower(),
                      PageID = 0, //Only initial value, changed later?
   开发者_JS百科                };

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


Try:

page.Users = _context.Users.First(u => u.UserId == currentUser.UserID);

Regarding this:

Also, by the way, the compiler requires that I set PageID in the object initializer

That should not be true. What is the exact error message? Also, what is the type of the ID?

0

精彩评论

暂无评论...
验证码 换一张
取 消