c# - 在不同类型上映射/转换 Linq-to-Sql 的问题

标签 c# linq linq-to-sql casting mapping

也许有人可以提供帮助。

我想在映射的 Linq 类上使用不同的数据类型。

这是有效的:

 private System.Nullable<short> _deleted = 1;

 [Column(Storage = "_deleted", Name = "deleted", DbType = "SmallInt", CanBeNull = true)]
    public System.Nullable<short> deleted
    {
        get
        {
            return this._deleted;
        }
        set
        {
            this._deleted = value;
        }
    }

没问题。但是当我想为 bool 值添加一些逻辑时,就不行了,就像这样:

 private System.Nullable<short> _deleted = 1;

 [Column(Storage = "_deleted", Name = "deleted", DbType = "SmallInt", CanBeNull = true)]
    public bool deleted
    {
        get
        {
            if (this._deleted == 1)
            {
                return true;
            }
            return false;
        }
        set
        {
    if(value == true)

    {
                this._deleted = (short)1;
    }else
    {   
                this._deleted = (short)0;
    }
        }
    }

我总是遇到运行时错误:

[TypeLoadException: GenericArguments[2], "System.Nullable`1[System.Int16]", on 'System.Data.Linq.Mapping.PropertyAccessor+Accessor`3[T,V,V2]' violates the constraint of type parameter 'V2'.]

我无法将数据库更改为 bit.. 我需要在映射类中进行转换。

** 更新

根据 mmcteam 的说法,在未映射的方法中进行转换就可以了。 不太确定是否以这种方式使用 OR 映射,但它确实有效。

    private System.Nullable<short> _deleted = 1;

    public bool deleted
    {
        get
        {
            if (this._deleted == 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }
        set
        {
            if (value)
            {
                this._deleted = 1;
            }
            else
            {
                this._deleted = 0;
            }
        }
    }


    [Column(Storage = "_deleted", Name = "deleted", DbType = "SmallInt", CanBeNull = true)]
    private short? deleted_smallint
    {
        get
        {
            return this._deleted;
        }
        set
        {
            this._deleted = value;
        }
    }

** 注意/问题

您不能在 linq 查询上使用未映射的方法!

                 var result = from p in dc.Products
                               where p.enabled && !p.deleted 
                select p;

导致不支持的sql异常。没有 where 条件,数据会得到正确的值。

最佳答案

或者只需向您的行类添加一个属性并将前一个属性转换为 bool。

关于c# - 在不同类型上映射/转换 Linq-to-Sql 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2757444/

相关文章:

c# - 如何处理从 LINQ to SQL 中的存储过程返回的 NULLable Int 列

c# - 在 asp.net View 中显示对象列表

c# - 我可以在 C# 中使用无类型集合吗

c# - 使用 C# 的 XML 中的 SAML 断言

c# - 如何将多个 linq 查询组合成一个结果集?

c# - 检查 Linq where 子句中是否为 Null

c# - 如何在一台服务器上使用WebSocket并在同一局域网内的另一台PC上访问它?

c# - DateTime 对象 Entity Framework 上的动态 LINQ OrderBy 日期

c# - 方法 X 不支持转换为 SQL - bool 值和日期时间

c# - Linq to SQL Repository ~理论~ - 通用但现在使用 Linq to Objects?