问题描述
我有两个表
State(StateID int,StateName string)
City(CityID int,StateID int,CityName string)
我正在使用代码优先方法来开发MVC4.该代码用于州和城市模型为-
I am working on MVC4 with code first approach.The code,i am using for State and City Model is -
对于州:
[Key]
public int StateID{get;set;}
public string StateName{get;set;}
对于城市:
[Key]
public int CityID{get;set;}
[ForeignKey("State")]
public string StateID{get;set;}
public virtual State State{get;set;}
这段代码正在为State Table的StateID创建一个外键.我想要的所有东西都在工作,但是由于我是MVC的新手,所以我得到的以下代码也在做同样的事情.
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;}
这让我对正确的操作方式感到困惑...我们应该在 ForeignKey Annotation (即 State )中传递模型类名称,或者应该将其作为Property(属性) 州ID 我已经解决了有关此Annotation的各种问题,但是我仍然不确定上述代码的区别.任何建议将不胜感激.
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. StateIDI 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.
推荐答案
使用ForeignKey
属性时,您传递外键应指向的导航属性的名称.
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
这是使用属性的正确方法.传递给属性的"State"
与导航属性名称相对应.
This is the correct way to use the attribute. The "State"
you passed into the attribute corresponds to the navigation property name.
在第二个示例中,您的导航属性被命名为StateID
,这就是为什么[ForeignKey("StateID")]
在该实例中也起作用的原因.
In your second example, your navigation property was named StateID
, which is why [ForeignKey("StateID")]
also worked in that instance.
看看 MSDN 文档以获取更多信息.
Take a look at the MSDN documentation for more information.
这篇关于MVC中的外键注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!