0

Entity properties can be split across different tables, meaning that a single Entity can have it's columns mapped to different tables. How does one then, in code, retrieve the info on the particular table an entity property is mapped to.

foreach(PropertyInfo pi in typeof(DbContext).GetProperties())
            {
                if(pi.PropertyType.IsGenericType && pi.PropertyType.Name.Contains("DbSet"))
                {
                    var t = pi.PropertyType.GetGenericArguments().FirstOrDefault();
                    var tables = t.GetCustomAttributes(true).OfType<TableAttribute>();
                    foreach (var entityProperty in t.GetProperties())
                    {
                        if (entityProperty.GetCustomAttributes(true).OfType<RequiredAttribute>().Any<RequiredAttribute>())
                        {
                            var fieldname = entity.Name;

                             //I need to match this column with the table it belongs to here
                        }
                    }
                }
            }

So far, I have the code below to get at the entity property, from the object itself, how do I determine the particular table the current property is mapped to, in my database? Thanks in advance.

Kobojunkie
  • 6,375
  • 31
  • 109
  • 164
  • Are you looking for this: http://stackoverflow.com/a/9760774/1844389 or this: http://stackoverflow.com/a/6463557/1844389 or this:http://stackoverflow.com/a/7505974/1844389 – Bhushan Firake Jun 04 '13 at 03:07
  • Not really. I need to match each column/Field in my Entity to the table it belongs to so I can execute a query against the correct table for the particular field. – Kobojunkie Jun 04 '13 at 03:29
  • Isn't the ORM meant for querying the database? – Aron Jun 04 '13 at 03:44
  • This is at point of db object initialization. I want to add some constraints to database tables as they are created. – Kobojunkie Jun 04 '13 at 03:54
  • In that case it sounds like you are looking for http://stackoverflow.com/questions/2614941/unique-keys-in-entity-framework-4/16496291#16496291 – Aron Jun 04 '13 at 03:57

1 Answers1

0

Consider using the OR/M for the actual generation of the SQL you actually need.

var dbContext = new DbContext();
var objectContext = ((IObjectContextAdapter)dbContext).ObjectContext;
var set = objectContext.Set<Foo>();
var query = from x in set
            where {stuff}
            select new { x.Bar, x.Baz ...};
var objectQuery = (ObjectQuery)query;
var command = objectQuery.CommandText;
var parameters = objectQuery.Parameters;
Aron
  • 15,464
  • 3
  • 31
  • 64