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

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

Question

Using the Fluent API, I configured an entity that I had. On the properties, take note of the HasColumnOrder.

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
    }
}

I want to be able to discover an object's keys as part of a generic function so I can locate an entity utilizing

DbSet().Find()

the primary key values in the right sequence, which I must pass.

The ObjectContext can provide me with the key names, but I am unsure of how to obtain the order. Can anybody assist?

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

Accepted Answer

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

Add this if you're looking for the automatically produced keys.Where prior to theSelect :

.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

No need to add any code because this

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

only person

// 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