簡體   English   中英

實體框架提供列名作為字符串變量

[英]Entity Framework providing column names as string variable

我正在尋找獲得這樣的東西的方法:

string _col1 = "first name";
string _name;
var query = from c in ctx.Customers select c;
_name = query.FirstOrDefault().[_name];

據我所知,我只能獲得強類型字段名稱,但我想將它們作為字符串變量提供。

我不確定EF是否為您提供了根據屬性的字符串名稱獲取屬性值的方法,但您可以使用反射。

string name = typeof(Customer)
    .GetProperty("first name")
    .GetValue(query.First(), null) as string;

我猜你正在處理的EF課叫做Customer

你需要使用反射。 如果您嘗試按動態選擇的列進行過濾,則可以嘗試以下方法:

string propertyName
string keyword

ParameterExpression parameter = Expression.Parameter(typeof(YourType), "x");
Expression property = Expression.Property(parameter, propertyName);
Expression target = Expression.Constant(keyword);
Expression containsMethod = Expression.Call(property, "Contains", null, target);
Expression<Func<YourType, bool>> lambda =
   Expression.Lambda<Func<YourType, bool>>(containsMethod, parameter);

var companies = repository.AsQueryable().Where(lambda);

我你要做的是選擇一個特定的列,然后你可以使用相同的原理生成lamba表達式並在select中使用它(減去條件)

var companies = repository.AsQueryable().Where(whatever).Select(lambda);

出於某種原因,它對我不起作用。

這是我類似的工作解決方案:

string name = null;

// Select the PropertyInfo of the column.
PropertyInfo propertyInfo = query.First().GetType().GetProperty("first name");

if (propertyInfo != null)
{
  try
  {
    // Select the content of the column.
    name = pi.GetValue(query.First(), null).ToString();
  }
  catch (Exception)
  { 
    // Continue with null-string.
  }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM