在 LINQ to SQL 中将枚举值作为存储过程(数据函数)参数传递
正如这个问题中提到的,“LINQ to SQL允许表映射自动转换通过指定列的类型来回枚举 - 这适用于字符串或整数。”但是,当我使用存储过程(而不是自动生成的 SQL)创建和更新实体时,我遇到了麻烦。
在我的数据库中,我有一个表 Users,其列 Role 类型为 int。我还有一个存储过程 CreateUser,它接受 int 类型的参数 @role。我希望用户角色由 C# 代码中的枚举角色表示。我可以将自动生成的 User 类上的 Role 属性的类型从 int 更改为 Role,但随后项目拒绝编译,因为 Role 属性的类型与数据函数角色参数的类型不匹配(对应于 @我的存储过程中的角色参数)。数据函数参数类型是由 LINQ to SQL 自动生成的,我找不到任何方法来更改它们。
我正在考虑将 Role 属性保留为 int,将其重命名为 RoleValue 之类的名称,将其设为私有,并添加另一个执行 int-enum 转换的 Role 类型的公共属性。但似乎应该有更好的方法。
As mentioned in this question, "LINQ to SQL allows table mappings to automatically convert back and forth to Enums by specifying the type for the column - this works for strings or integers." However, I am having trouble with this when using stored procedures (instead of auto-generated SQL) to create and update entities.
In my database I have a table Users with a column Role of type int. I also have a stored procedure CreateUser which accepts a parameter @role of type int. I want user roles to be represented by an enum Role in my C# code. I can change the type of the Role property on the autogenerated User class from int to Role, but then the project refuses to compile because the type of the Role property doesn't match the type of the data function role parameter (corresponding to the @role parameter in my stored procedure). The data function parameter types are autogenerated by LINQ to SQL and I can't find any way to change them.
I'm considering leaving the Role property as an int, renaming it to something like RoleValue, making it private, and adding another public property of type Role which performs the int-enum conversion. But it seems like there ought to be a better way.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
打开 DBML 文件,单击“角色”字段。属性窗口将有一个地方可以指定服务器类型以及.NET 类型。这是其工作原理的示例:
从字符串映射枚举
答案表明它适用于 VARCHAR 和 TINYINT,因此它也应该适用于 INT。最困难的部分可能是记住放入正确的名称空间。祝你好运!
open your DBML file, click on the Role field. the properties window will have a place to specify the server type, as well as the .NET type. here's an example of how it works:
Mapping Enum from String
the answers indicate it works with VARCHARs and TINYINTs so it should work fine with INT as well. the hardest part is probably remembering to put in the right namespace. good luck!
您可以重载 CreateUser 方法。
使用 T4 模板使用后端数据库的实时数据生成 Enumberable 类也很常见。这样它就可以与 Int 匹配,并且您无需手动更新它。
You can overload the CreateUser method..
It's also common to use T4 Templates to generate the Enumberable class using real-time data from the backend database. That way it matches up with the Ints and you won't have to update it manually.