Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Required attribute for foreign keys

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?

like image 445
mosquito87 Avatar asked Feb 27 '13 10:02

mosquito87


People also ask

What is required for an attribute to be a foreign key?

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.

What is a foreign key attribute?

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.

Can a foreign key have multiple attributes?

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.)

How do you set a foreign key in EF?

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.


1 Answers

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.

like image 194
Jayantha Lal Sirisena Avatar answered Oct 12 '22 19:10

Jayantha Lal Sirisena