# IT:AD:EF/CodeFirst:HowTo:Define Models/Properties # * [[../|(UP)]] {{indexmenu>.#2|nsort tsort}} ## Examples: Properties ## The following just specify contraints on size, key, etc. #### Primary Key #### It's done automatically if you the fieldname is called `Id` or `TheEntitityId`, but if you can't use that field name: modelBuilder.Entity() .HasKey(ma => ma.ManagerCode); #### Composite Keys #### Use an anonymous object: modelBuilder.Entity() .HasKey(t => new { t.DepartmentID, t.Name }); #### MaxLength #### modelBuilder.Entity().Property(ma => ma.Name) .HasMaxLength(20); #### Required #### modelBuilder.Entity().Property(dp => dp.Name) .IsRequired(); #### Ignore #### You can ignore calculated columns: modelBuilder.Entity().Ignore(t => t.Budget); #### Mapping to a different Column #### modelBuilder.Entity().Property(t => t.Name) .HasColumnName("DepartmentName"); ### CheckList: Class Properties ### * MUST: mark Scalar Properties as `virtual` to enable improved Change Tracking (by going from Snapshot CT to Proxy POCO Change Tracking, which is based on `IPOCO`/`IEntityWithChangeTracker`). * MUST: mark Collection Navigation Properties as `virtual` to enable lazy loading. * MUST: Navigation Collection properties must implement `ICollection` * SHOULD: As we are working with proxies, can use `private set` for Id, etc: * `public string Id {get; private set;}` * CONSIDER: For properties that need to ignored: * DataAnnotations: `[Ignore]` (see [[IT/AD/Code First/DataAnnotations/]]). * FluentAPI: within `DataContext.OnModelCreating()`: `modelBuilder.Entity().Ignore(t => t.Budget);` (see [[IT/AD/Code First/FluentAPI/Properties/]]) * CONSIDER: For derived calculated properties *that need to be saved*, use empty sets: * `public FullName {get {return _first + " " + _last;} set {}}` * CONSIDER: If you have to turn of Id autogeneration: * DataAnnotations: ? (see [[IT/AD/Code First/DataAnnotations/]]) * FluentAPI: within `DataContext.OnModelCreating()`: `modelBuilder.Entity().Property(t => t.ID).HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);` (see [[IT/AD/Code First/FluentAPI/Properties/]]) #### Reference: Property Related FluentAPI #### * [http://msdn.microsoft.com/en-us/library/hh295847(v=vs.103).aspx](http://msdn.microsoft.com/en-us/library/hh295847(v=vs.103).aspx)