使用字符串变量引用Entity列

时间:2015-01-29 16:17:09

标签: c# entity-framework validation

我正在尝试为使用Entity Framework的应用程序创建数据驱动验证 在我的验证表中,我想存储:

  • 字段名称(FreightToBillCustomer)
  • 验证条件(>)
  • 验证值(5)
  • 错误消息(对账单客户的运费必须小于5)
  • 会员名称(FreightToBillCustomer)

我将在下面使用这些。

if (  FreightToBillCustomer > 5)
{ 
    ValidationResult vr = new ValidationResult("Freight to bill customer must  be less than 5",new[] { "FreightToBillCustomer" });
    errors.Add(vr);
}

当我将字段名称作为字符串变量传递时,我的问题出现了,我如何翻译/转换为实体框架识别的列。我的目标是获取验证记录列表并在实体的分部类中循环它们,并在SaveChanges()事件之前执行验证。

1 个答案:

答案 0 :(得分:1)

您可以使用以下代码:

var assembly = typeof(NameOfAnyClassInTheAssembly).Assembly;

string typeName = NameOfClass;
var type = assembly.GetType(typeName);

// Create an instance of this type
var instance = Activator.CreateInstance(type);

// Get the property of this type
var property = type.GetProperty("NameOfProperty");

// Fetch the property value
var propertyValue = property.GetValue(instance, null);

只需用您的变量替换NameOf ....变量。

有关工作示例,请参阅以下链接:

Reflection example

相关问题