Composite Primary Key using Data Annotations

When developing domain classes in Entity Framework using Code First Approach, the default code conventions creates a primary key of a property named “ID” or <ClassName>ID. But if you wanted to use another property as your primary key , you can use DataAnnotations and decorate the property using “Key” attribute.

What is more interesting is that you could actually create a composite primary key. All you need to do is use another attribute along with “Key”, namely, “Column”.

image

The above example creates a Table with a Composite Primary Key made up of Dept1 and Dept2. Entity Framework is surely letting the developers live in the comfort zone of Visual Studio rather than dig up SQL Server.

Advertisement

One thought on “Composite Primary Key using Data Annotations

  1. I see you don’t monetize bytelanguage.net,
    don’t waste your traffic, you can earn extra bucks every month with
    new monetization method. This is the best adsense alternative for
    any type of website (they approve all websites), for more info simply search in gooogle: murgrabia’s tools

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s