我试图在C#MVC中重写一个VB.NET WebForms应用程序。在使用Entity Framework实例化类时,我遇到了其中一个属性的问题。
我的数据库中有一个列" VATInclusive",其类型为' int'。原始应用程序隐式转换了" 1"或" 0"到"真"或" false",但在我的应用程序中尝试执行此操作时,出现以下错误:
' VATInclusive'物业' Shop'无法设置为 ' System.Int32'值。您必须将此属性设置为非null值 类型' System.Boolean'。
当其他应用程序使用该表时,我无法简单地更改数据库中的类型。我尝试使用以下代码转换值,但似乎只返回false,无论数据库是否有" 0"或者" 1" ......有人能建议解决这个问题吗?
[Column("VATInclusive")]
private int _VATInclusive { get; set; }
[NotMapped]
public bool VATInclusive
{
get
{
if (_VATInclusive == 0)
{
return false;
}
else
{
return true;
}
}
set
{
if(_VATInclusive == 0)
{
this.VATInclusive = false;
}
else
{
this.VATInclusive = true;
}
}
}
答案 0 :(得分:5)
根据所提供答案的一些建议,我已经纠正了这个问题。问题在于setter访问器以及_VATIncusive属性。通过将代码更改为以下代码,我设法使系统按预期工作。
但是,我觉得这不是最好的方法,但似乎工作正常......
编辑:编辑:根据Ryan和hvd的建议,我已经减少了访问权限。
编辑:我不确定将这两个属性设置为公开的含义。但我不认为这会成为一个问题。
[Column("VATInclusive")]
public int _VATInclusive { get; set; }
[NotMapped]
public bool VATInclusive
{
get
{
return _VATInclusive != 0;
}
set
{
_VATInclusive = value ? 1 : 0;
}
}
答案 1 :(得分:1)
你的二传手上有一些拼写错误。我认为你的意思是:
set
{
if(value == false)
{
_VATInclusive = 0;
}
else
{
_VATInclusive = 1;
}
}
基本上,"价值"表示传入setter的bool值(转换为整数)。 _VATInclusive是您想要在引擎盖下修改的实际对象。
答案 2 :(得分:1)
您无法为自己分配一个setter访问器 - 这将始终导致StackOverflowException。在下面的代码中:
set
{
if(_VATInclusive == 0)
{
this.VATInclusive = false;
}
else
{
this.VATInclusive = true;
}
}
每次分配this.VATInclusive时,控制流都返回到set访问器的开头。这显然永远无法完成。
答案 3 :(得分:1)
如果您将列存储为位,Entity Framework会自动将其作为布尔值查询。
答案 4 :(得分:0)
在set
中,您需要与value
进行比较:
if (value == 0)