I'm just thinking about a foreign key attribute in Entity Framework (using code first approach). I want to ensure that this foreign key is always set, in other words: It should be required.
Is using the "Required"-attribute/data annotation a clean solution for this? Or should this data annotation be used for user input only?
A foreign key is a column (or combination of columns) in a table whose values must match values of a column in some other table. FOREIGN KEY constraints enforce referential integrity, which essentially says that if column value A refers to column value B, then column value B must exist.
A foreign key is defined as an attribute or set of attributes in a relation whose values match a primary key in another relation. The syntax to add such a constraint to an existing table is defined in SQL:2003 as shown below.
That's impossible. A FOREIGN KEY constraint can only point to one table and each table can only have one PRIMARY KEY constraint. Or you can have multiple FOREIGN KEY constraints on the same column(s) referencing one PRIMARY KEY of a (different) table each. (Rarely useful.)
The [ForeignKey(name)] attribute can be applied in three ways: [ForeignKey(NavigationPropertyName)] on the foreign key scalar property in the dependent entity. [ForeignKey(ForeignKeyPropertyName)] on the related reference navigation property in the dependent entity.
I don't think you need to have required attribute in the data annotation . If you have declared it as
public int ForeignKeyName{get;set;}
It will take as required by EF. And if it
public int? ForeignKeyName{get;set;}
it will be taken as optional(nullable) by entity framework Conventions . I'm not sure what kind of framework you are using for the web(front end Ex: asp.net mvc). Depend on that you need to think about that input level.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With