Problem with Mapping/Casting Linq-to-Sql on differ

2019-05-06 03:05发布

问题:

maybe someone can help.

I want to have on mapped Linq-Class different Datatype.

This is working:

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

Sure thing. But no when i want to place some logic for boolean, like this:

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

I get always runtime error:

[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'.]

I can't change the database to bit.. I need to have casting in mapping class.

** Update

According to mmcteam, casting in unmapped method does the trick. Not so sure if it is ment to be using the OR Mapping that way, but it works.

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

** NOTICE/PROBLEM

You can't use the not mapped methods on linq queries!

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

causes not supported sql exception. Without the where condition, data comes out with correct values.

回答1:

Or just add one more property to your row class and cast previous one to bool.



回答2:

Don't you want this:

[Column(Storage = "_deleted", Name = "deleted", DbType = "Bit", CanBeNull = false)] 
public bool deleted ...

Instead of this:

[Column(Storage = "_deleted", Name = "deleted", DbType = "SmallInt", CanBeNull = true)] 
public bool deleted ...

?