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

c# entity-framework-5 entity-framework-6

Question

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?

1
1
2/10/2016 8:35:48 AM

Accepted Answer

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"))
1
1/15/2015 2:48:31 PM

Popular Answer

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 );


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow