问题
I have two tables as
State(StateID int,StateName string)
City(CityID int,StateID int,CityName string)
I am working on MVC4 with code first approach.The code,i am using for State and City Model is -
For State:
[Key]
public int StateID{get;set;}
public string StateName{get;set;}
For City:
[Key]
public int CityID{get;set;}
[ForeignKey("State")]
public string StateID{get;set;}
public virtual State State{get;set;}
This code is creating a foreignkey for StateID of State Table.All i wanted is working but as i am new in MVC i got the following code is also doing the same thing.
[ForeignKey("StateID")]
public string Stateid{get;set;}
public virtual State StateID{get;set;}
It made me lil confuse about what is the correct way for doing...We should pass Model Class name in ForeignKey Annotation i.e. State or it should be Property i.e. StateID I went through various questions already asked here regarding this Annotation.But i am still not sure about the difference of above codes. Any suggestion would be appreciated.
回答1:
When using the ForeignKey attribute, you pass the name of navigation property the foreign key should point to.
So, in your first example you have:
[ForeignKey("State")]
public string StateID { get; set; }
public virtual State State { get; set; } // This is your navigation property
This is the correct way to use the attribute. The "State" you passed into the attribute corresponds to the navigation property name.
In your second example, your navigation property was named StateID, which is why [ForeignKey("StateID")] also worked in that instance.
Take a look at the MSDN documentation for more information.
来源:https://stackoverflow.com/questions/21765817/foreign-key-annotation-in-mvc