obaylis
obaylis

Reputation: 3034

Entity framework composite primary key - how to get order of columns

I have an entity which I have configured using the Fluent API. Notice the HasColumnOrder on the properties.

public class SomeEntityMap : EntityTypeConfiguration<SomeEntity>
{
    public SomeEntityMap ()
    {
        // Primary Key
        this.HasKey(t => new { t.Id, t.BarId });

        this.ToTable("SomeEntity", "Foo");
        this.Property(t => t.Id).HasColumnName("Id").HasColumnOrder(0);
        this.Property(t => t.BarId).HasColumnName("BarId").HasColumnOrder(1);

        // additional properties removed for brevity
    }
}

As part of a generic method, I want to be able to find an entity's keys so I can find an entity using

DbSet().Find()

to which I need to pass the primary key values in the correct order.

I can get the key names from the ObjectContext but I cannot see where to get the order. Can anyone help?

Upvotes: 2

Views: 2366

Answers (2)

Saneesh kunjunni
Saneesh kunjunni

Reputation: 548

Not need to Add code as this

// Primary Key
this.HasKey(t => new { t.Id, t.BarId });

Only user

// Primary Key
this.HasKey(t =>t.Id );

Upvotes: 1

ocuenca
ocuenca

Reputation: 39326

Try this:

   var adapter = (IObjectContextAdapter)db;
   var objectContext = adapter.ObjectContext;
   var objectSet = objectContext.CreateObjectSet<SomeEntity>();
   var entitySet = objectSet.EntitySet;
   var keyNames = entitySet.ElementType.KeyMembers             
                 .Select(e => e.Name).ToList();

If you want to find the auto generated keys, then add this Where before the Select:

.Where(p => p.MetadataProperties.Any(m => m.PropertyKind == PropertyKind.Extended
                                  && Convert.ToString(m.Value) == "Identity"))

Upvotes: 1

Related Questions