如何在 LinqToSQL 查询中使用我的枚举?
- 作者: 大美人困兽之斗
- 来源: 51数据库
- 2022-12-15
问题描述
我的数据库表中有一个字段用于存储枚举值,例如:
I have a field in my database table that use to store an enumeration value, e.g.:
create table MyTable ( ... Status tinyint not null, ... )
在我的 C# 类中
public enum TStatus : byte {
Pending = 1
Active = 2,
Inactive = 3,
}
public TStatus MyStatus {
get { return (TStatus)Status; }
set { Status = (byte)value; }
}
现在我想编写一个使用 MyTable 的 MyStatus 属性的 Linq 查询,例如
now I want to write a Linq query that uses the MyStatus property of MyTable e.g.
var q = MyDataContext.GetTable<MyTable>().Where(t => t.MyStatus == TStatus.Active);
当然,Linq 不知道如何将 MyStatus 解释为 SQL.我需要对 MyStatus 做什么才能让它在 LinqToSQL 中工作?
but of course, Linq doesn't know how to interpret MyStatus as SQL. What do I need to do to MyStatus in order for it to work in LinqToSQL?
推荐答案
查看此链接:
http://dotnet.org.za/hitong/archive/2008/08/06/using-enums-with-linq-to-sql.aspx
当链接失效时——至少对我来说这个链接失效了——这是重要的部分:
As links die - and at least for me this one did die - here is the important part:
[将列添加到实体时] 默认情况下,类型将显示为int (System.Int32)",但您可以将其更改为枚举的完全限定类型(在我的情况下,ConsoleApplication1.CustomerType).但是,为了完全定位它,您必须添加全局标识符,如下所示: global::ConsoleApplication1.CustomerType ,因此将其按原样(但与您的命名空间等效)输入文本框
[When adding the column to the entity] by default, the Type will come up as an "int (System.Int32)", but you can change it to the fully-qualified type of the enum (in my case, ConsoleApplication1.CustomerType). BUT, in order to locate it fully, you have to add the global identifier, as follows: global::ConsoleApplication1.CustomerType , so type that as is (but the equivalent for your namespace) into the textbox
- 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 包还原找不到包,没有源
