ASP.NET MVC C#Entity转换为未知类型的未知属性

时间:2015-11-11 15:08:09

标签: c# asp.net asp.net-mvc linq

我必须从一个未知的实体中获取属性的类型,然后将字符串值解析为我传递给该操作的值。

代码示例:

public ActionResult QuickEdit(int pk, string name, string value)
{
    var pext = Db.ProjectExtensions.Find(pk); 
    if (ModelState.IsValid)
    {
        var propertyInfo = pext.GetType().GetProperty(name); //get property
        propertyInfo.SetValue(pext, value, null); //set value of property

        Db.SaveChangesWithHistory(LoggedEmployee.EmployeeId);

        return Content("");
    }
}

不幸的是,它仅在属性为string类型时才有效。如何解析我为其设置值的属性类型的值?

谢谢!

更新

我试过了:

propertyInfo.SetValue(pext, Convert.ChangeType(value, propertyInfo.PropertyType), null);

我得到了

{"Invalid cast from 'System.String' to 'System.Nullable`1[[System.Double, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]'."}

2 个答案:

答案 0 :(得分:0)

试试这个(不过,正如DavidG在评论中提到的那样,你可以在你的模型上设置任何属性,这不是一个好主意):

public ActionResult QuickEdit(int pk, string name, string value)
{
    var pext = Db.ProjectExtensions.Find(pk); 
    if (ModelState.IsValid)
    {
        var propertyInfo = pext.GetType().GetProperty(name); //get property
        propertyInfo.SetValue(pext, Convert.ChangeType(value, propertyInfo.PropertyType), null);

        Db.SaveChangesWithHistory(LoggedEmployee.EmployeeId);

        return Content("");
    }
}

答案 1 :(得分:0)

我采用了ataravati的解决方案并对其进行了一些修改以使用可空类型。

以下是解决方案:

Get-ChildItem -Directory | Sort-Object -Property {[int]$_.Name}