I am trying to map a composite key for an entity.
public class Customer
{
public int CustomerId { get; set; }
public virtual List<CustomerImage> CustomerImages { get; set; }
}
And its Map:
public class CustomerMap : EntityTypeConfiguration<Customer>
{
public CustomerMap()
{
HasKey(t => t.CustomerId);
ToTable(DbConstants.k_CustomersImageTable);
}
}
An Image:
public class Image
{
public int ImageId { get; set; }
}
And its map:
public class ImageMap : EntityTypeConfiguration<Image>
{
public ImageMap()
{
HasKey(t => t.ImageId);
ToTable(DbConstants.k_ImagesTable);
}
}
And the navigation property:
public class CustomerImage
{
public int CustomerId { get; set; }
public int ImageId { get; set; }
public virtual Customer CustomerRelated { get; set; }
public virtual Image ImageRelated { get; set; }
}
And its map:
public class CustomerImageMap : EntityTypeConfiguration<CustomerImage>
{
public CustomerImageMap()
{
HasKey(t => new { t.CustomerId, t.ImageId });
Property(t => t.CustomerId).IsRequired().HasColumnOrder(0);
Property(t => t.ImageId).IsRequired().HasColumnOrder(1);
HasRequired(t => t.ImageRelated).WithMany().HasForeignKey(x => x.ImageId);
HasRequired(p => p.CustomerRelated)
.WithMany(p => p.CustomerImages)
.WillCascadeOnDelete(false);
ToTable(DbConstants.k_CustomersImageTable);
}
}
But I keep getting the following exception:
One or more validation errors were detected during model generation:
System.Data.Entity.Edm.EdmEntityType: : EntityType 'CustomerImage' has no key defined. Define the key for this EntityType.
System.Data.Entity.Edm.EdmEntitySet: EntityType: EntitySet 'CustomerImages' is based on type 'CustomerImage' that has no keys defined.
However, if I define the composite key with data annotations, which is not very nice, it works perfectly:
public class CustomerImage
{
[Key, Column(Order = 0)]
public int CustomerId { get; set; }
[Key, Column(Order = 1)]
public int ImageId { get; set; }
}
And its map:
public class CustomerImageMap : EntityTypeConfiguration<CustomerImage>
{
public CustomerImageMap()
{
ToTable(DbConstants.k_CustomersImageTable);
}
}
I've tried many variations of the definitions but none seems to work. Any idea? Is it EF bug?