我在数据库表中有一个字符串列,它映射到代码中的枚举.在我的 dbml 文件中,当我将类型"设置为 MyTypes.EnumType
时,我收到以下错误:
I have a string column in a database table which maps to an Enum in code. In my dbml file when I set the "Type" to MyTypes.EnumType
I get the following error:
错误 1 DBML1005:DbType 'VarChar(50) NOT NULL' 和类型 'Table1' 的列 'EnumCol' 中的类型 'MyTypes.EnumType' 不是支持.
Error 1 DBML1005: Mapping between DbType 'VarChar(50) NOT NULL' and Type 'MyTypes.EnumType' in Column 'EnumCol' of Type 'Table1' is not supported.
这个问题:LINQ to SQL 字符串到枚举表示我正在尝试做的事情是可能的,但它是如何完成的?
This question: LINQ to SQL strings to enums indicates that what I am trying to do is possible, but how is it done?
好奇 - 它应该可以工作 IIRC;我会看看我是否可以做一个简单的例子 - 但是,您可能想要检查您是否拥有完全限定的枚举名称(即包括命名空间).
Curious - it should work IIRC; I'll see if I can do a quick example - however, you might want to check that you have the fully-qualified enum name (i.e. including the namespace).
[更新] 从这里似乎 RTM 版本在解析枚举时附带了一个错误.建议的一种解决方法(在该页面上)是添加 global::
前缀.如果没有这个解决方法,它对我来说很好用,所以它可能在 3.5 SP1 中得到修复?如果枚举在同一命名空间中使用非限定名称,则据称它在 3.5 中也能正常工作.
[update] From here it seems that the RTM version shipped with a bug when resolving the enum. One workaround suggested (on that page) was to add the global::
prefix. It works fine for me without this workaround, so maybe it is fixed in 3.5 SP1? It also allegedly works fine in 3.5 if you use the unqualified name if the enum is in the same namespace.
[示例] 是的,工作正常:使用 Northwind,我为运输国家/地区定义了一个枚举:
[example] Yup, worked fine: with Northwind, I defined an enum for the shipping country:
namespace Foo.Bar
{
public enum MyEnum
{
France,
Belgium,
Brazil,
Switzerland
}
}
然后我将 dbml 编辑为:
I then edited the dbml to have:
<Column Name="ShipCountry" Type="Foo.Bar.MyEnum" DbType="NVarChar(15)" CanBeNull="true" />
这产生了:
private Foo.Bar.MyEnum _ShipCountry;
//...
[Column(Storage="_ShipCountry", DbType="NVarChar(15)", CanBeNull=true)]
public Foo.Bar.MyEnum ShipCountry
{ get {...} set {...} }
最后写了一个查询:
using (DataClasses1DataContext ctx = new DataClasses1DataContext())
{
var qry = from order in ctx.Orders
where order.ShipCountry == Foo.Bar.MyEnum.Brazil
|| order.ShipCountry == Foo.Bar.MyEnum.Belgium
select order;
foreach (var order in qry.Take(10))
{
Console.WriteLine("{0}, {1}", order.OrderID, order.ShipCountry);
}
}
工作正常;结果:
10250, Brazil
10252, Belgium
10253, Brazil
10256, Brazil
10261, Brazil
10287, Brazil
10290, Brazil
10291, Brazil
10292, Brazil
10299, Brazil
这篇关于从字符串映射枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!