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