Skip to content

Attribute (Data Annotations) mapping for composite primary keys #11003

@ygoe

Description

@ygoe

I'd like to declare a primary key that consists of multiple columns only with the Key attribute, just like for all other keys and as it was supported in EF6. This is the only situation when I have to go to the OnModelCreating method in another file to find out about the basic structure of the entity.

Currently I have to write this scattered code outside of where the entity is defined:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
	base.OnModelCreating(modelBuilder);
	modelBuilder.Entity<MyEntity>()
		.HasKey(e => new { e.KeyColumn1, e.KeyColumn2 });
}

I'd prefer to keep it simple and in a single place, the entity class:

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

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

I could imagine it would be helpful to get rid of the slightly unintuitive Column attribute just for this and define the order where it belongs and is used, the Key attribute, like in [Key(Order = 1)].

I'm wondering why there isn't already an issue for this. I have found one or two issues that might be similar but I don't understand them well enough to consider them a match for this topic. Also I couldn't see this mentioned in the sparse information I could find about the upcoming EF Core 2.1 so I have to assume it's not included in the next version.

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions