将日志对象保存为sqllite no id只插入一条记录?

时间:2017-06-21 19:25:18

标签: c# sqlite ormlite-servicestack

using ServiceStack;
using ServiceStack.OrmLite;

public static string SqliteFileDb = "~/App_Data/db.sqlite".MapHostAbsolutePath();

private static void CreateX(Message msg)
{
//Using Sqlite DB- improved
 var dbFactory = new OrmLiteConnectionFactory(SqliteFileDb, SqliteDialect.Provider);
// Wrap all code in using statement to not forget about using db.Close()
using (var db = dbFactory.Open())
{
db.CreateTableIfNotExists<Message>();                    
Message notex = new Message();
notex.Content = msg.Content;
notex.Datestamp = msg.Datestamp;
notex.Facility = msg.Facility;
notex.Hostname = msg.Hostname;
notex.LocalDate = msg.LocalDate;
notex.RemoteIP = msg.RemoteIP;
notex.Severity = msg.Severity;
db.Save(notex))                  
db.Close();              
}
}

 public class Message
{
        public FacilityType Facility { get; set; }
        public SeverityType Severity { get; set; }
        public DateTime Datestamp { get; set; }
        public string Hostname { get; set; }
        public string Content { get; set; }
        public string RemoteIP{ get; set; }
        public DateTime LocalDate { get; set; }
}

有人可以建议如何解决这个问题 我保存系统日志消息的情况 使用servicestack orm到sqlite数据库。

似乎只有一个对象可用 并获得更新。没有新记录 创建

1 个答案:

答案 0 :(得分:2)

如果您没有在OrmLite中提供主键,OrmLite将假定主键是表中的第一个属性,在这种情况下不是您想要的。您需要通过使用[PrimaryKey]属性对其进行注释来告诉OrmLite它应该用于主键的属性,或者只需添加数据库将自行填充的自动递增主键,例如:

public class Message
{
    [AutoIncrement]
    public in Id { get; set; }
    public FacilityType Facility { get; set; }
    public SeverityType Severity { get; set; }
    public DateTime Datestamp { get; set; }
    public string Hostname { get; set; }
    public string Content { get; set; }
    public string RemoteIP{ get; set; }
    public DateTime LocalDate { get; set; }
}

同样db.Close()在using语句中是多余的,在这种情况下,您没有想要与OrmLite的高级Save() API一起使用的功能,所以您应该只有:

using (var db = dbFactory.Open())
{
    db.CreateTableIfNotExists<Message>();                    
    Message notex = new Message();
    notex.Content = msg.Content;
    notex.Datestamp = msg.Datestamp;
    notex.Facility = msg.Facility;
    notex.Hostname = msg.Hostname;
    notex.LocalDate = msg.LocalDate;
    notex.RemoteIP = msg.RemoteIP;
    notex.Severity = msg.Severity;
    db.Insert(notex);
}