I have a class that looks like this.
public class MyClass
{
public Object1 Object1 { get; set; }
public Object2 Object2 { get; set; }
public int Order { get; set; }
public DateTime Created { get; set; }
}
MyClass is a connection table with two additional columns.
Entity Mapping:
public class MyClassMap : EntityTypeConfiguration<MyClass>
{
public MyClassMap()
{
ToTable("dbo.MyClass");
HasKey(pc => new { pc.Object1.Id, pc.Object2.Id });
Property(x => x.Order).IsOptional();
Property(x => x.Created).HasColumnType("DateTime").IsRequired();
}
}
The problem occurs when I want create a composite primary key for MyClass. I want the primary key like this:
HasKey(pc => new { pc.Object1.Id, pc.Object2.Id });
The problem is that this is not allowed. An anonymous type cannot have multiple properties with the same name
I could of course name my Id property on class Object1 to Object1Id and my Id property on class Object2 to Object2Id but I don't want that.
I could also add another property on MyClass called Id and use this as primary key but want to avoid that too.
Is there an alternative way to solve this problem?
Mathew (https://stackoverflow.com/users/219933/mathew) gave me some hints.
Class needs to look like this(added Object1Id and Object2Id):
public class MyClass
{
public Object1 Object1 { get; set; }
public int Object1Id { get; set; }
public Object2 Object2 { get; set; }
public int ObjectId2 { get; set; }
public int Order { get; set; }
public DateTime Created { get; set; }
}
Entity mapping:
public class MyClassMap : EntityTypeConfiguration<MyClass>
{
public MyClassMap ()
{
this.ToTable("dbo.MyClass");
HasKey(pc => new { pc.Object1Id, pc.Object2Id});
HasRequired(x => x.Object1).WithMany().HasForeignKey(x => x.Object1Id);
HasRequired(x => x.Object2).WithMany().HasForeignKey(x => x.Object2Id);
}
}
This does not solve my problem with duplicate key name column named Id but I hope Entity Framework will support primary key like this in the future:
HasKey(pc => new { pc.Object1.Id, pc.Object2.Id});