VB.NET自动实现属性参数错误与标识符缺失问题解决指引
VB.NET模型类处理含特殊字符的数据库字段解决方案
在VB.NET中,标识符(比如属性名)不能直接包含-、/这类特殊字符,这就是你遇到“Identifier expected”和“Auto-implemented properties cannot have parameters”错误的原因。以下两种方法可以解决这个问题:
方法一:用方括号包裹特殊属性名
VB.NET允许用方括号[]将包含特殊字符的属性名括起来,让编译器将其识别为合法标识符,直接对应数据库字段名。修正后的代码如下:
Public Class PivotSizeStocksin Public Property [-]() As Integer Public Property [XS/SS]() As Integer Public Property [XXL/2L]() As Integer Public Property [XXXL/3L]() As Integer Public Property [XXXXL/4L]() As Integer End Class
这种方式直接映射字段名,写法简单,适合不需要ORM框架的场景。
方法二:用特性映射数据库字段名
如果使用ORM框架(比如Entity Framework),更推荐给属性起符合VB命名规范的名称,再通过特性指定对应的数据库字段名,让代码更易读维护。示例如下:
Imports System.ComponentModel.DataAnnotations.Schema Public Class PivotSizeStocksin <Column("-")> Public Property Minus As Integer <Column("XS/SS")> Public Property XsSs As Integer <Column("XXL/2L")> Public Property Xxl2L As Integer <Column("XXXL/3L")> Public Property Xxxl3L As Integer <Column("XXXXL/4L")> Public Property Xxxxl4L As Integer End Class
这里的<Column("字段名")>特性会告诉ORM框架,该属性对应数据库中指定名称的字段,既规避了VB标识符的限制,又保持了代码的规范性。
内容的提问来源于stack exchange,提问作者user22579796
相关产品推荐
相关产品推荐

