Thursday, November 20, 2014

Random MVC EF stuff

"The Required attribute is not needed for value types such as DateTime, int, double, and float. Value types cannot be assigned a null value, so they are inherently required. "

"

The ForeignKey Attribute

When there is a  one-to-zero-or-one relationship or a  one-to-one relationship between two entities (such as betweenOfficeAssignment and Instructor), EF can't work out which end of the relationship is the principal and which end is dependent.  One-to-one relationships have a reference navigation property in each class to the other class. TheForeignKey Attribute can be applied to the dependent class to establish the relationship. If you omit the ForeignKey Attribute, you get the following error when you try to create the migration:
Unable to determine the principal end of an association between the types 'ContosoUniversity.Models.OfficeAssignment' and 'ContosoUniversity.Models.Instructor'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations."



..later one we learn:

"The course entity has a foreign key property DepartmentID which points to the related Department entity and it has aDepartment navigation property. The Entity Framework doesn't require you to add a foreign key property to your data model when you have a navigation property for a related entity.  EF automatically creates foreign keys in the database wherever they are needed. But having the foreign key in the data model can make updates simpler and more efficient. For example, when you fetch a course entity to edit, the  Department entity is null if you don't load it, so when you update the course entity, you would have to first fetch the  Department entity. When the foreign key propertyDepartmentID is included in the data model, you don't need to fetch the Department entity before you update."


No comments: