从字符串映射枚举
- 作者: 关婕妍
- 来源: 51数据库
- 2022-12-08
问题描述
我在数据库表中有一个字符串列,它映射到代码中的枚举.在我的 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
- C#通过fleck实现wss协议的WebSocket多人Web实时聊天(附源码)
- 团队城市未满足要求:MSBuildTools12.0_x86_Path 存在
- 使用 MSBuild.exe 在发布模式下构建 C# 解决方案
- 当我发布 Web 应用程序时,AfterPublish 脚本不运行
- 构建时 T4 转换的产品仅在下一个构建中使用
- ASP.NET Core Application (.NET Framework) for Windows x64 only error in project.assets.json
- 新的 .csproj 格式 - 如何将整个目录指定为“链接文件"到子目录?
- 如何将条件编译符号(DefineConstants)传递给 msbuild
- MSBuild 支持 Visual Studio 2017 RTM 中的 T4 模板
- NuGet 包还原找不到包,没有源
