How do I map a composite primary key in Entity Framework 4 code first?

前端 未结 4 2018
挽巷
挽巷 2020-12-08 09:45

I\'m getting to grips with EF4 code first, and liking it so far. But I\'m having trouble mapping an entity to a table with a composite primary key.

The configuration

4条回答
  •  误落风尘
    2020-12-08 10:01

    I will try to explain it step by step, using the following Entity

    public class Account
    {
        public int AccountId1 { get; set; }
        public int AccountId2 { get; set; }
        public string Description { get; set; }
    }
    
    1. Create a class derived from the EntityTypeConfiguaration Object to override the conventions

      class AccountEntityTypeConfiguration : EntityTypeConfiguration
      {
      
          public AccountEntityTypeConfiguration()
          {
            // The Key
            // The description of the HasKey Method says
            // A lambda expression representing the property to be used as the primary key.
            // If the primary key is made up of multiple properties then specify an anonymous type including the properties.
            // Example C#: k => new { k.Id1, k.Id2 }
            // Example VB: Function(k) New From { k.Id1, k.Id2 }
            this.HasKey(k => new { k.AccountId1, k.AccountId2 } );  // The Key
      
            // Maybe the key properties are not sequenced and you want to override the conventions
            this.Property(p => p.AccountId1).HasDatabaseGeneratedOption(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.None);
            this.Property(p => p.AccountId2).HasDatabaseGeneratedOption(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.None);
      
            this.Property(p => p.Description).IsRequired();  // This property will be required
            this.ToTable("Account");  // Map the entity to the table Account on the database
          }
      }
      
    2. When create the class derived from the DbContext Object, override OnModelCreating Method and add a new AccountEntityTypeConfiguration object to the Configurations of the model Builder.

      public class MyModelAccount : DbContext
      {
          public DbSet Accounts { get; set;}
      
          protected override void OnModelCreating(DbModelBuilder modelBuilder)
          {
              // Add a new AccountEntityTypeConfiguration object to the configuration of the model, that will be applied once the model is created. 
              modelBuilder.Configurations.Add(new AccountEntityTypeConfiguration());
          }
      
      }
      

    Hope it helps you!

提交回复
热议问题