也许有人可以提供帮助。
我想在映射的 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/