Search code examples
asp.net-mvcasp.net-mvc-5

What is the purpose of the [Key] attribute on a Primary Key in an asp.net MVC class?


I have read in various places, eg

http://techfunda.com/howto/132/primary-key-and-foreign-key-relationship-in-model

...that if you don't call the Id property in your model "Id" or "id" you need to add the annotation [Key], eg

[Key]
public int MyKey { get; set; }

...to it to tell the compiler it's the primary key in the database.

It seems like this may only be a requirement for Code First sites - although I can't find anything conclusive either way.

What is the purpose of [Key] and when should it be used?

Do I need to decorate any primary keys in models that are not called "Id" even when not building a Code First MVC site?


Solution

  • When you run code first and use this:

    public class MyClass{
        [Key]
        public int MyKey { get; set; }
    }
    

    This will create in your database:

    Table >> dbo.MyClass Column >> MyKey IDENTITY NOT NULL