¿Cómo puedo asignar una clave principal compuesta en Entity Framework 4 código primero?

StackOverflow https://stackoverflow.com/questions/2733254

Pregunta

Estoy llegando a enfrentarse con código EF4 primero, y gustando hasta ahora. Pero estoy teniendo problemas para mapeo una entidad a una tabla con una clave principal compuesta.

La configuración que he intentado ve así:

public SubscriptionUserConfiguration()

    {
                Property(u => u.SubscriptionID).IsIdentity();
                Property(u => u.UserName).IsIdentity();
    }

Lo que lanza esta excepción: No es posible deducir una clave para el tipo de entidad SubscriptionUser '.

¿Qué me falta?

¿Fue útil?

Solución

También es posible usar

HasKey(u => new { u.SubscriptionID, u.UserName });

Editar:

Una de las limitaciones que he encontrado es que el siguiente no lo hacen el trabajo:

public ProjectAssignmentConfiguration()
{
    HasKey(u => u.Employee.EmployeeId);
    HasKey(u => u.Project.ProjectId);
}

o

public ProjectAssignmentConfiguration()
{
    HasKey(u => new { u.Employee.EmployeeId, u.Project.ProjectId });
}

Entonces, ¿cómo configurar una entidad donde el tabla de unión tiene una clave principal que se compone de claves externas?

Otros consejos

Voy a tratar de explicar paso a paso, utilizando la siguiente Entidad

public class Account
{
    public int AccountId1 { get; set; }
    public int AccountId2 { get; set; }
    public string Description { get; set; }
}
  1. Crea una clase derivada de la Object EntityTypeConfiguaration<TEntity> para anular las convenciones

    class AccountEntityTypeConfiguration : EntityTypeConfiguration<Account>
    {
    
        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. Cuando crear la clase derivada de la Object DbContext, override OnModelCreating Método y añadir un nuevo objeto AccountEntityTypeConfiguration a las configuraciones del modelo de constructor.

    public class MyModelAccount : DbContext
    {
        public DbSet<Account> 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());
        }
    
    }
    

Espero que te ayude!

También puede utilizar el atributo Column

public class UserProfileRole
{
    [Key, Column(Order = 0)]
    public int UserId { get; set; }

    [Key, Column(Order = 1)]
    public int RoleId { get; set; }
}

lo resolvió: que debería usar Haskey, no de identidad. Estos trabajos:

public SubscriptionUserConfiguration()
{
     HasKey(u => u.SubscriptionID);
     HasKey(u => u.UserName);
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top