Skip to content

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

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.

Activity

  1. ajcvickers commented on Feb 21, 2018

    @ajcvickers
    Contributor

    @ygoe We have been tracking the general issue of new attributes for things like this in issue #10111. However, I will leave this open as a specific case we should cover.

  2. added this to the Backlog milestone on Feb 21, 2018
  3. cilerler commented on May 9, 2019

    @cilerler

    @ajcvickers this issue becomes a big deal upon OData usage, is there any chance to bump the priority up.

  4. ajcvickers commented on May 9, 2019

    @ajcvickers
    Contributor

    @cilerler Can you provide some more details as to why OData changes things here?

  5. cilerler commented on May 9, 2019

    @cilerler

    @ajcvickers in my case database may have new fields, and time to time I need to add those to code. The easy workaround for me is generating the new DbContext through scaffolding and compare it with the previously generated one.

    Since scaffolding uses .HasKey instead of [Key], OData is not able to identify those and forcing me to use it in GetEdmModel() as below, which requires manual verification each time.

    namespace MyProject.Models
    {
        [Table("Items")]
        public partial class Item
        {
            [Column("ID")]
            public long Id { get; set; }
            public string Notes { get; set; }
        }
    
        [Table("ProcessorSettings")]
        public partial class ProcessorSettings
        {
            [StringLength(50)]
            public string Name { get; set; }  // <= IF it would set the [Key] for this property, I wouldn't need to define it later
            [StringLength(2)]
            public string Code { get; set; }
            [StringLength(500)]
            public string Description { get; set; }
        }
    }

    EF

    // ...
    public virtual DbSet<ProcessorSetting> ProcessorSettings { get; set; }
    public virtual DbSet<Item> Items { get; set; }
    // ...
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        // ...
    	modelBuilder.Entity<ProcessorSettings>(entity =>
    	{
    		entity.HasKey(e => new { e.Name, e.Code });
    		entity.Property(e => e.Name)
    			.IsUnicode(false)
    			.ValueGeneratedNever();
                    entity.Property(e => e.Code).IsUnicode(false);
    		entity.Property(e => e.Description).IsUnicode(false);
    		entity.Property(e => e.Value).IsUnicode(false);
    	});
    
    	modelBuilder.Entity<Item>(entity =>
    	{
    		entity.Property(e => e.Notes).IsUnicode(false);
    	});
        //...
    }

    OData

    public static IEdmModel GetEdmModel()
    {
        var builder = new ODataConventionModelBuilder();
        // ...
        builder.EntitySet<Item>("Item");  // Automatically locates the `Id` column as `Key`
        builder.EntitySet<ProcessorSetting>("ProcessorSettings").EntityType.HasKey(e => new { e.Name, e.Code });
        // ...
        return builder.GetEdmModel();
    }
  6. ajcvickers commented on May 9, 2019

    @ajcvickers
    Contributor

    @cilerler I don't see any composite keys in that example.

  7. cilerler commented on May 9, 2019

    @cilerler

    @ajcvickers updated as .HasKey(e => new { e.Name, e.Code });

  8. ajcvickers commented on May 9, 2019

    @ajcvickers
    Contributor

    @cilerler Can you show the attributes that would be needed by OData to configure this as a composite key, including how the order of the two parts of the composite key is defined?

  9. cilerler commented on May 9, 2019

    @cilerler

    @ajcvickers Just having [Key] on properties would be fine, there is no order so far. You may see more details in here https://stackoverflow.com/a/27538581/439130

  10. ajcvickers commented on May 9, 2019

    @ajcvickers
    Contributor

    @cilerler That is something we can never support because the order of the properties in the composite key is critical for correctness. I'm actually very surprised that OData allows this given they they presumably have the same problem since the order is also critical to the OData model, but maybe it is constrained in some other way that isn't apparent here.

  11. smitpatel commented on May 9, 2019

    @smitpatel
    Contributor

    maybe it is constrained in some other way that isn't apparent here.

    Based on stackoverflow post, OData is actually not caring about order at all. It's all about which are the key properties which should be bound when calling Get method. Order of properties does not matter because ODataRoute attribute specify which parameter should be bound with which key property.

    @cilerler - You are free to add KeyAttribute to your model to make OData work. The EF model will not complain since Fluent API is overriding data annotation based configuration.
    We will never scaffold KeyAttribute when generating EntityType from database until the ordering of properties issue is resolved out.

    The OData issue does not change anything in this issue.

  12. ajcvickers commented on May 9, 2019

    @ajcvickers
    Contributor

    Thanks @smitpatel for clarifying that.

  13. cilerler commented on May 9, 2019

    @cilerler

    Thanks, @smitpatel.

    We will never scaffold KeyAttribute when generating EntityType from database until the ordering of properties issue is resolved out.

    I was under the impression that I was asking if you may make the issue priority, did I sound different?

    I got into the details because of @ajcvickers comments. As I mentioned above, it already works the way it is, and I have to do a manual check about the keys each time I do scaffolding which is an error-prone step.

    Just wanted to nudge to get attention on this issue. 😁

  14. 16 remaining items

  15. added a commit that references this issue on Mar 4, 2022
    6b9adaa
  16. added 2 commits that reference this issue on Mar 9, 2022
    af7cc98
    0209b59
  17. modified the milestones: 7.0.0, on Mar 15, 2022
  18. changed the title [-]KeyAttribute support for composite primary key[/-] [+]Attribute (Data Annotations) mapping for composite primary keys[/+] on Apr 18, 2022
  19. modified the milestones: , 7.0.0 on Nov 5, 2022
  20. removed their assignment
    on Sep 1, 2024
  21. added theissue type on Jun 15, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions