I have a basic question in MVC3. I am starting to write out Models for my project. I understand Models are in a way tables in my relational database layer. How do I specify a class attribute (field in a table) as a FK. I know the [Key] qualifier for PKs. For example :
public class Class1
{
[Key]
public int MyID { get; set; }
public string myDes {get;set;}
}
In the above example MyId is a PK in Class1. How do I use this MyId in a another class and use it as FK.
EDIT: Is this correct?
public class Class2
{
[Key]
public int SecondID { get; set; }
[ForeignKey("MyId")]
public string MyId{ get; set; }
}
Class1 and Class2 are in two different .cs files.
Store an instance of the associated record (or a list of associated records for one-to-many or many-to-many relationships).
This may change based how you are persisting the data to the DB, but in general this is the OO way to do it.
I do this using EF 4.1 Code First, and the resulting DB contains a Foreign Key into the associated table.
Edit in response to your latest comment (regarding the ForeignKeyAttribute) so I can use the better code formatting in the answer:
According to the MSDN entry for the
ForeignKeyAttribute(http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.foreignkeyattribute(v=vs.103).aspx#Y198), the name you pass into theForeignKeyAttributeis the name of the corresponding navigation property or foreign key property on the same class.For example:
The
ForeignKeyattribute in the above code snippet identifies theForeignObjectIDproperty as a foreign key for theForeignObjectproperty. You will still need an instance of the foreign object in your class.You can also use the
ForeignKeyattribute on the navigation property, just pass in the name of the foreign key property to the attribute: