2010-03-08 69 views
0

我正在使用ASP.NET MVC2和Entity Framework。我会稍微简化一下情况;希望它会使它更清晰,不会更混乱!显式转换在默认模型绑定中不起作用

我有一个控制器操作来创建地址,国家是一个查找表(换句话说,国家和地址类之间有一对多的关系)。为了清楚起见,Address类中的字段称为Address.Land。而且,出于下拉列表的目的,我得到了Country.CountryID和Country.Name。我想了解Model vs. Input validation。所以,如果我打电话给下拉字段formLand - 我可以让它工作。但是,如果我叫场土地(即,匹配地址类变量) - 我收到以下错误:

"The parameter conversion from type 'System.String' to type 'App.Country' failed because no type converter can convert between these types."

OK,这是有道理的。一个字符串(CountryID)来自表单,并且绑定器不知道如何将其转换为Country类型。所以,我写了转换器:

namespace App { 
    public partial class Country { 
     public static explicit operator Country(string countryID) { 
      AppEntities context = new AppEntities(); 
      Country country = (Country) context.GetObjectByKey(
       new EntityKey("AppEntities.Countries", "CountryID", countryID)); 
      return country; 
     } 
    } 
} 

FWIW,我试过了显式和隐式。我从控制器测试它 - Country c = (Country)"fr" - 它工作正常。但是,在发布视图时,它从不会被调用。我在模型中获得了相同的“无类型转换器”错误。

任何想法如何暗示模型联编程序有一个类型转换器? 谢谢

+0

我的$ 0.02:绑定查看/编辑模型,而不是实体。 – 2010-03-08 21:27:06

+0

我不会不同意 - 但我在这里描述的下拉菜单的问题将完全相同 – Felix 2010-03-08 22:11:04

+0

不是。您的视图模型属性将是一个“字符串”,而不是一个实体。绑定会起作用。然后您可以使用字符串上的查询更新实体。 – 2010-03-09 02:31:57

回答

2

类型转换器与显式或隐式转换不同,它是一个在各种类型之间转换值的对象。

我想你需要创建TypeConverterCountry和其他类型之间的转换继承的类,并应用TypeConverterAttribute到您的类来指定转换器的使用方法:

using System.ComponentModel; 

public class CountryConverter : TypeConverter 
{ 
    // override CanConvertTo, CanConvertFrom, ConvertTo and ConvertFrom 
    // (not sure about other methods...) 
} 

[TypeConverter(typeof(CountryConverter))] 
public partial class Country 
{ 

... 

} 
+0

哇!这是朝着正确方向迈出的巨大一步......我不知道TypeConverter。非常感谢你。我也看了微软的HowTo:http://msdn.microsoft.com/en-us/library/ayybcxe5.aspx 现在发生了一件有趣的事情。很明显,EF生成CountryConverter,但它是从EntityObject派生的,显然与TypeConverter没有任何关系(奇怪,如果是的话)。所以,我创建了LandConverter类,用[TypeConverter(typeof(LandConverter))]装饰了Country。 (续...) – Felix 2010-03-08 22:07:19

+0

我还没有到达LandConverter的断点:CanConvertFrom或LandConverter:ConvertFrom。但是,该异常听起来有点不同: “从类型'System.String'到类型'App.CountryConverter'的参数转换失败,因为没有类型转换器可以在这些类型之间进行转换。“ 注意CountryConverter是生成的类,不是我的LandConverter,所以现在我更加困惑了, (hm - 每15秒只允许1条评论;) – Felix 2010-03-08 22:08:15