0

I have a POCO entity as follows:

public class Entity {
    public int Id { get; set; }
    public int? OtherEntityId { get; set; }
    public virtual OtherEntity OtherEntity { get; set; }
}

The code-first configuration is as follows:

conf.HasKey(e => e.Id).ToTable("entities");
conf.Property(e => e.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
conf.HasOptional(e => e.OtherEntity).WithMany().HasForeignKey(e => e.OtherEntityId);

I'd like to be able to retrieve the database generated option & FK properties at runtime. For example, I can dynamically retrieve the primary key property like so:

var keyProperties = objectContext.CreateObjectSet<Entity>()
    .EntitySet
    .ElementType
    .KeyMembers
    .Select(km => typeof(Entity).GetProperty(km.Name));
    .ToList()

How can I do this (I am using EF 4.3.1)?

ChaseMedallion
  • 20,860
  • 17
  • 88
  • 152

1 Answers1

2

For looking up the foreign key properties, just use @Ashraf's answer on this SO question.

I couldn't find anything similar for finding the DatabaseGenerated attribute while keeping the Fluent API. If you're willing to put a data annotation on your POCO, you should be able to grab it using reflection, just like any other attribute (similar to what's being done on this blog post):

typeof(Entity).GetProperties().Where(prop => prop.GetCustomAttributes(typeof (DatabaseGeneratedAttribute), true).Any());

This will return an IEnumerable><PropertyInfo>, which you should then be able to play around with.

Community
  • 1
  • 1
Corey Adler
  • 15,897
  • 18
  • 66
  • 80