EF code first automatic foreign key association problem
I've got a basic grip of the latest version of EF code first via this tutorial - http://www.asp.net/mvc/tutorials/getting-started-with-mvc3-part4-cs but I'm slightly confused about one aspect and wondering if anybody could shed light on it? To explain - there's a class called "Site" which I want to have a field called "HomePageId" which should then map to the "SitePage" object with that Id. Seems simple enough? But when EF creates the Db and the relationships it doesn't seem to understand this. I'm sure it's something I'm doing wrong - here's the code:
public class Site
{
public int SiteId { get; set; }
public string SiteName { get; set; }
public string SiteUrlPortion { get; set; }
// Relationship - SitePages
public virtual ICollection<SitePage> SitePages { get; set; }
// Relationship - HomePage
public int HomePageId { get; set; }
public virtual SitePage HomePage { get; set; }
}
public class SitePage
{
public int SitePageId { get; set; }
public string SitePageTitle { get; set; }
public string SitePageUrlPortion { get; set; }
// Relationship - Site
public int SiteId { get; set; }
public virtual Site Site { get; set; }
}
The "SitePage" class generates the relationship back to "Site" as you would expect. But what I've got in terms of columns in both tables not only doesn't make sense but the relationship from the code-side of things doesn't work a开发者_StackOverflow中文版s expected. (Eg when I give the "Site" a "HomePageId" the site's "HomePage" is null.
Obviously there's little out there in terms of documentation because this is still in development, but just wondering if anybody had any ideas? Do I need to start decorating the properties with Attributes? Or am I asking it to understand something that it never will?!
Thanks to all in advance. I'll persevere anyway and post back anything I find obviously. Rob
try marking your HomePage property with a ForeignKey attribute like this
[Foreignkey("HomePageId")]
public virtual SitePage HomePage { get; set; }
you could also use the fluent configuration but don't remember that offhand
It is probably a limitation in EF. That EF can only handle one relationship between 2 tables.
You have 2 relationships between the tables, to the list of site pages and to the home page.
try removing this line:
public virtual SitePage HomePage { get; set; }
You still have the homepageid, so in a way this information was redundant.
精彩评论