Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework Code First Read Only Key

In EF 4.1 RC1, I have a simple entity like say Category, with a property ID int. Can I make that a read only property and still have it work?

If not, how do you protect the PK/FK?

like image 631
Sam Avatar asked Mar 17 '11 02:03

Sam


People also ask

How do I mention primary key in Entity Framework Code First?

The Code First primary key convention is: Property with name " Id " or {class name} + " Id " will act as the primary key for that entity. If you will run the application, it will create _MigrationHistory and Students tables where " StudentId " is the primary key of the Students table.

How do I set primary key in Entity Framework?

Configuring a primary key By convention, a property named Id or <type name>Id will be configured as the primary key of an entity. Owned entity types use different rules to define keys. You can configure a single property to be the primary key of an entity as follows: Data Annotations.

Does Entity Framework require primary key?

The Entity framework will not support to have a table without primary key, but we can overcome this issue by accessing the table with additional column via a view and marking the new column as Primary in entity framework. Entity Framework requires primary keys for entities.

How do I create a foreign key in Entity Framework Code First?

To create Foreign Key, you need to use ForeignKey attribute with specifying the name of the property as parameter. You also need to specify the name of the table which is going to participate in relationship.


1 Answers

One way is to define your ID property like this:

public int ID { get; internal set; }

... then define your DbContext class in the same assembly as the "Category" class. It'll have write access to the property, but classes outside of the assembly won't.

If you need to define your DbContext in a separate assembly, you can use the InternalsVisibleTo attribute to let that assembly see the internals of your "Category" class.

like image 179
Matt Hamilton Avatar answered Oct 06 '22 23:10

Matt Hamilton