简体   繁体   中英

How to determine database table field and get the value with Entity Framework

I'm looking for a method to getdatabase table's field with variable thing. I wrote a stupid and unworking method to explain what I need:

using (var dbContext = new db_ReadyEngine_MSSQL())
   {
     string nameOfField = "UserName";

     var table = dbContext.tbl_User;
     foreach (var x in table)
       {
         string fieldValue = x.nameOfField;
       }
}

Here, I'm trying to determining column name which it nameOfField ...

您可以使用列名从DataTable调用数据,例如:

Object o = dataTable.Rows[0][nameOfField];

try this:

   List<string>values = new List<string>();
    using (var dbContext = new db_ReadyEngine_MSSQL())
   {

     values = (from s in dbContext.tbl_User select s.Username).ToList();

   }
   return values

Assuming I am reading your question correctly, you want to get the value of a column, whose name is only known at runtime?

If so, have a look at the code below. It will pull the properties from the object type, search for the one that matches the nameOfField value, and then pull attempt to pull a value from it.

foreach (var x in table)
{
    var fieldValue = x.GetType().GetProperties().Where(a => a.Name == nameOfField).Select(p => p.GetValue(x, null)).FirstOrDefault();
}

U can use Reflection to get value of Property using its String Name

using (var dbContext = new db_ReadyEngine_MSSQL())
   {
     string nameOfField = "UserName";

     var table = dbContext.tbl_User;
     foreach (var x in table)
       {
         string fieldValue = typeof(x).GetProperty(nameOfField ).GetValue(x, null) as string;
       }
}

You can use Entity SQL for this without typing the query itself:

IEnumerable<object> GetFieldValues<T>(DbContext context, string fieldName)
    where T : class
{
    var oc = ((IObjectContextAdapter)context).ObjectContext;
    ObjectQuery<T> q = oc.CreateObjectSet<T>();
    return q.Select("it." + fieldName)
            .AsEnumerable()
            .Select(x => x[0]);
}

The trick is that an ObjectSet (the predecessor, sort of, or DbSet ) can easily be cast to an ObjectQuery , which is the base of Entity SQL. By default, the command text uses "it" as alias for the table in the query, so if you want the value of one specific field, you must prefix it by the alias, and there you go.

The Select returns a DbDataRecord . The first value from this record is returned.

The advantage of this method over others is that it only queries the requested field from the database.

Of course, if you know the type of the field in question up front, you can make a strong-typed version of this method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM