问题 如何在不使用sqlite raw语句/ conn.execute()的情况下为Sqlite.net设置默认值


我知道这是一个愚蠢的问题,但我无法在任何地方找到答案。 如何为列中的默认值设置 sqlite.net 模型? 这是我的模型类:

public class ItemTaxes
{
    [PrimaryKey]
    public string Sku { get; set;}
    public bool IsTaxable { get; set;}// How to set IsTaxable's default value to true?
    public decimal PriceTaxExclusive { get; set;}
}

我想设置默认值 不是空的 柱 IsTaxable 至 真正,我该怎么做?顺便说一句我不想使用原始的sql语句,即 conn.execute();

谢谢。


2840
2017-09-08 17:50


起源

你想要将默认值设置为..你可以创建一个类或方法,使用这样的东西将ItemTaxes字段的值设置为你想要的任何东西 PropertyInfo[] properties = clsObject.GetType().GetProperties(); 然后执行foreach循环,例如,如果值默认为null,则可以将它们设置为string.Empty,例如执行以下操作 - MethodMan
public static void ConvertNullToStringEmpty <T>(this T clsObject)其中T:class {PropertyInfo [] properties = clsObject.GetType()。GetProperties(); // typeof(T).GetProperties(); foreach(属性中的var info){//如果是字符串且为null,则设置为String.Empty if(info.PropertyType == typeof(string)&& info.GetValue(clsObject,null)== null){info.SetValue( clsObject,String.Empty,null); }}} - MethodMan
我不认为这有一个属性。为什么不在构造函数中设置值? - Postlagerkarte
Vielen Dank fuer beide @DJ KRAZE和Postlagerkarte,尤其是DJ KRAZE。我最终得到了这个解决方案:私人布尔? _isTaxable; public bool IsTaxable {get {if(_isTaxable == null){_ isTaxable = true; } return _isTaxable; } set {_isTaxable = value; }} - macio.Jun


答案:


有点晚了,但对于那些来这里寻找答案的人:

public class ItemTaxes
{
    [NotNull, Default(value: true)]
    public bool IsTaxable { get; set; }
}

10
2018-02-17 20:56



我正在使用PCL Blanck App(Xamarin.Forms Portable),我不能写[Default(value:true)],因为它在此解决方案中不可用。 - Ashish Jain
哪个版本的SQLite.Net有这个属性? - Geograph
@Geograph它已经开启了 oysteinkrog / SQLite.Net-PCL 以来 版本3.0.1。 - Gabriel Rainha
如果我这样做,我的列被设置为字符串值“True”,因为它只使用默认值的字符串表示(是的,您可以在SQLite中的整数列中存储字符串)。这种行为似乎毫无意义。 - Elte Hupkes
不适用于这个praeclarum的sqllite-net at github.com/praeclarum/sqlite-net - ScottRFrost