我正在尝试映射实体的复合键。
public class Customer
{
public int CustomerId { get; set; }
public virtual List<CustomerImage> CustomerImages { get; set; }
}
及其地图:
public class CustomerMap : EntityTypeConfiguration<Customer>
{
public CustomerMap()
{
HasKey(t => t.CustomerId);
ToTable(DbConstants.k_CustomersImageTable);
}
}
一个图像:
public class Image
{
public int ImageId { get; set; }
}
及其地图:
public class ImageMap : EntityTypeConfiguration<Image>
{
public ImageMap()
{
HasKey(t => t.ImageId);
ToTable(DbConstants.k_ImagesTable);
}
}
以及导航属性:
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; }
}
及其地图:
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);
}
}
但我不断收到以下异常:
在模型生成过程中检测到一个或多个验证错误:
System.Data.Entity.Edm.EdmEntityType: : EntityType 'CustomerImage' 没有定义键。定义此 EntityType 的键。
System.Data.Entity.Edm.EdmEntitySet:EntityType:EntitySet“CustomerImages”基于未定义键的类型“CustomerImage”。
However,如果我用数据注释定义复合键,这不是很好,但它工作得很好:
public class CustomerImage
{
[Key, Column(Order = 0)]
public int CustomerId { get; set; }
[Key, Column(Order = 1)]
public int ImageId { get; set; }
}
及其地图:
public class CustomerImageMap : EntityTypeConfiguration<CustomerImage>
{
public CustomerImageMap()
{
ToTable(DbConstants.k_CustomersImageTable);
}
}
我尝试过许多定义的变体,但似乎都不起作用。
任何想法?是EF的bug吗?