問題描述
我在數據庫表中有一個字符串列,它映射到代碼中的枚舉.在我的 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模板網!