实体框架C#将int转换为bool [英] Entity Framework C# convert int to bool

查看:1195
本文介绍了实体框架C#将int转换为bool的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试用C#MVC重新编写VB.NET WebForms应用程序。在使用Entity Framework实例化类时,属性之一出现了问题。

I'm attempting to re-write a VB.NET WebForms application in C# MVC. I'm having an issue with one of the properties when using Entity Framework to instantiate a class.

我的数据库 VATInclusive中有一列,其类型为'int'。原始应用程序将 1或 0隐式转换为 true或 false,但是在我的应用程序中尝试执行此操作时,出现以下错误:

I have a column in my database "VATInclusive", which is of type 'int'. The original application implicitly converted a "1" or "0" to "true" or "false", but when trying to do this in my application, I get the following error:


不能将'Shop'上的'VATInclusive'属性设置为
'System.Int32'值。您必须将此属性设置为类型为'System.Boolean'的非空值

The 'VATInclusive' property on 'Shop' could not be set to a 'System.Int32' value. You must set this property to a non-null value of type 'System.Boolean'.

我不能只需在其他应用程序使用该表时更改数据库中的类型。我尝试使用以下代码转换该值,但无论数据库是 0还是 1,它似乎只会返回false。有人可以提出解决方案吗?

I can't simply change the type in the database as other applications make use of the table. I've tried using the following code to convert the value, but it seems to only return false, regardless of whether the database has a "0" or a "1"... Can anybody suggest a solution to this?

    [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;
            }
        }
    } 


推荐答案

根据所提供答案的一些建议,我已纠正了该问题。问题出在设置访问器以及_VATIncusive属性上。通过将代码更改为以下代码,我设法使系统按预期运行。

Following some advice from the answers provided, I have rectified the issue. The issue lay with the setter accessor and also with the _VATIncusive property. By changing the code to the following I have managed to get the system to work as I expected.

但是,我觉得这不是最好的方法,但是似乎工作正常...

However, I feel that this isn't the best approach, but it appears to be working correctly...

EDIT EDIT :我已经按照

编辑:我不确定同时将这两个属性设置为公开的含义。但是我不认为这会成为问题。

EDIT : I'm not sure of the implications of having both properties set to public. But I don't think this is going to be an issue.

    [Column("VATInclusive")]
    public int _VATInclusive { get; set; }

    [NotMapped]
    public bool VATInclusive
    {
        get
        {
            return _VATInclusive != 0;
        }
        set 
        {
            _VATInclusive = value ? 1 : 0;
        }
    }

这篇关于实体框架C#将int转换为bool的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆