0

实体属性可以在不同的表中拆分,这意味着单个实体可以将其列映射到不同的表。然后如何在代码中检索实体属性映射到的特定表上的信息。

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

到目前为止,我有下面的代码来获取实体属性,从对象本身,我如何确定当前属性映射到的特定表,在我的数据库中?提前致谢。

4

1 回答 1

0

考虑使用 OR/M 来生成您实际需要的 SQL。

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;
于 2013-06-04T03:53:51.020 回答