ZVenue
ZVenue

Reputation: 5027

Model question in MVC3

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.

Upvotes: 0

Views: 273

Answers (1)

Kyle Trauberman
Kyle Trauberman

Reputation: 25684

Store an instance of the associated record (or a list of associated records for one-to-many or many-to-many relationships).

public MyOtherObject MyObject { get; set; }

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 the ForeignKeyAttribute is the name of the corresponding navigation property or foreign key property on the same class.

For example:

public class MyClass
{
    // This is a "Navigation Property"
    public MyOtherClass ForeignObject { get; set; }

    // This is a "Foreign Key Property"
    [ForeignKey("ForeignObject")]
    public int ForeignObjectID { get; set; }
}

The ForeignKey attribute in the above code snippet identifies the ForeignObjectID property as a foreign key for the ForeignObject property. You will still need an instance of the foreign object in your class.

You can also use the ForeignKey attribute on the navigation property, just pass in the name of the foreign key property to the attribute:

public class MyClass
{
    // This is a "Navigation Property"
    [ForeignKey("ForeignObjectID")]
    public MyOtherClass ForeignObject { get; set; }

    // This is a "Foreign Key Property"
    public int ForeignObjectID { get; set; }
}

Upvotes: 1

Related Questions