问题
I have a 1-to-0..1 relationship defined in an Entity Framework code first model like this:
public class Album
{
public int AlbumId { get; set; }
public int StampId { get; set; }
public Stamp Stamp { get; set; }
// other properties
}
public class Stamp
{
public int StampId { get; set; }
public int AlbumId { get; set; }
[Required]
public Album Album { get; set; }
// other properties
}
So.. an album has 0..1 stamps, a stamp always has exactly one album. The configuration I have here works nicely. However when I look at what columns are generated in the data base, I'm a bit unhappy: The foreign key is created in the Album
table.. which makes it a hard/slow to bulk-insert new Stamps, as you always need to alter the Album
table and update the StampId
Foreign Keys there. (That means I need change tracking to change those fields)
How can I tell Entity Framework to create the foreign key in the Stamp
table?
I'm also not sure what role the declaration of the navigation properties play in this context.. does it matter whether you have those properties defined in both directions?
回答1:
Ok, I figured it out using the nice examples I found here: http://www.entityframeworktutorial.net/code-first/configure-one-to-one-relationship-in-code-first.aspx
The trick is to use the 'AlbumID' foreign key in the 'Stamps' table as primary key. So that implies that the Stamp Ids will not be the primary key, and that the primary key will have 'gaps' for the IDs which do not exist. So in other words, by doing that you are guarantee that one Album has only one Stamp. Since this concept is a bit irritating, one can still simulate a UID 'StampID' which increments whenever you add a new entry.
So in my example that would be:
public class Album
{
public int AlbumId { get; set; }
public Stamp Stamp { get; set; }
// other properties
}
public class Stamp
{
[Index(IsUnique = true)] // another UID, just to follow the naming pattern
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int StampId { get; set; }
[Key, ForeignKey("Album")] // The PK, taken as FK from the associated Album
public int AlbumId { get; set; }
[Required] // the required attribute just makes validation errors more readable
public Album Album { get; set; }
// other properties
}
来源:https://stackoverflow.com/questions/36742272/entity-framework-code-first-10-1-change-foreign-key-location