简体   繁体   English

ASP.NET MVC中的动态类型转换编辑操作:如何在不引发异常的情况下处理多种数据类型?

[英]Dynamic typecasting in asp.net mvc Edit action: how can I handle multiple datatypes without throwing an exception?

I'm making a generic MVC viewer/editor for data objects I've designed, modeled after ActiveRecord. 我正在为按ActiveRecord建模的我设计的数据对象制作通用的MVC查看器/编辑器。

The data objects are completely generic, they can have primary keys that are strings, ints, int16s, whatever the database uses (the persistence layer at this organization uses all sorts of datatypes for primary keys and I want this MVC "browser/editor" to handle them all). 数据对象是完全通用的,它们可以具有字符串,int,int16s等主键,无论数据库使用什么(该组织的持久层都将各种数据类型用作主键,我希望此MVC“浏览器/编辑器”用于处理所有)。

Creating the Edit links in the Index view is easy: 在“索引”视图中创建“编辑”链接很容易:

Response.Write("<td>" + Html.ActionLink("Edit", "Edit", new { id = pkValue }) + "</td>");

The problem is on the other side, in the Edit action: 问题在另一方面,在“编辑”操作中:

public ActionResult Edit(object id)

Anything other than a string throws an exception when I try to use id as the sole element of an array of parameters to a static "select" method invoked via reflection to retrieve a hydrated data object to edit from the database: 当我尝试将id用作通过反射调用以从数据库检索水合数据对象以进行编辑的静态“ select”方法的参数“数组”的唯一数组时,除字符串以外的任何方法都会引发异常:

object[] parameters = { id };
list = (List<T>)select.Invoke(null, parameters);

I know the CLR type of the parameter, and I know the "real" type of object id . 我知道参数的CLR类型,也知道object id的“真实”类型。 Am I supposed to use some kind of gnarly case statement to do the type conversion manually, or is there a trick I can use to do the type conversion using the type of the parameter? 我应该使用某种粗糙的case语句手动进行类型转换,还是可以使用参数类型来进行类型转换的技巧?

Can/Should I overload the ActionResult Edit() to take int , int16 , int32 , etc? 是否可以/应该将ActionResult Edit()重载为intint16int32等?

What should I do here to ensure that no matter the "real" type of id , I can pass it into the database without an exception being thrown? 我应该在这里做什么以确保无论id为“真实”类型,我都可以将其传递到数据库中而不会引发异常?

Here's what I've tried so far: 到目前为止,这是我尝试过的方法:

I made my generic controller take two type parameters, one for the data object and another for the primary key datatype: 我使通用控制器采用两个类型参数,一个用于数据对象,另一个用于主键数据类型:

public class CoreDataController<t,T> : Controller  where T:IDataObjectBase<T>

Then I tried this move: 然后我尝试了此举:

id = (t)id;
object[] parameters = { id};

BZZZRT! BZZZRT! "the specified cast is invalid". “指定的演员表无效”。 id is "2" and t is int? id"2"tint?

Can you supply more code details for the select method and the Stored Proc or Query that you are executing to the pull data. 您是否可以提供关于select方法以及您要对pull数据执行的Stored Proc或Query的更多代码详细信息。

I would currently suggest to pass the value of id parameter to select in the following manner. 我目前建议以以下方式传递id参数的值进行选择。

if(id != null)
  Select(id.ToString());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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