我的表将包含许多重复的字符串,例如域。为了最小化数据库大小,我只想在其他表中保存唯一域并在主表中使用域 id。
一直以来我都是手动完成的,但不久前我发现 SQLite 可以自动完成。
现在我尝试使用带有“FOREIGN”键的多对一关系,但没有成功。也许我做错了什么。
示例代码
表类:
public class Domains
{
public Domains() { }
public Domains(string domain) { this.Domain = domain; }
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
[Unique, MaxLength(64)]
public string Domain { get; set; }
}
public class Statistics
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
public int Timestamp { get; set; }
[ForeignKey(typeof(Domains))]
public int DomainId { get; set; }
public int Status { get; set; }
[ManyToOne(CascadeOperations = CascadeOperation.All)]
public Domains Domain { get; set; }
}
主要代码:
static void Main(string[] args)
{
var dbFile = "stats.db";
var domains = new[] { "stackoverflow.com", "superuser.com", "serverfault.com", "google.com", "microsoft.com" };
var statList = new List<Statistics>();
var sqlBase = new SQLiteConnection(dbFile);
sqlBase.Execute("PRAGMA foreign_keys = ON");
sqlBase.CreateTable<Domains>();
sqlBase.CreateTable<Statistics>();
Console.WriteLine(SQLite3.LibVersionNumber());
var runTimestamp = (int)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds;
foreach (var domain in domains)
{
HttpWebResponse resp = null;
var status = -1;
try
{
resp = (HttpWebResponse)WebRequest.Create("http://" + domain).GetResponse();
}
catch { };
status = (int)resp.StatusCode;
var stat = new Statistics();
stat.Domain = new Domains(domain);
stat.Status = status;
stat.Timestamp = runTimestamp;
statList.Add(stat);
}
sqlBase.InsertOrIgnoreAllWithChildren(statList); // Modification "INSERT" with "OR IGNORE"
Console.WriteLine(@"Table ""Domains""");
foreach (var table in sqlBase.Table<Domains>())
{
Console.WriteLine("Id: {0}\tDomain: {1}", table.Id, table.Domain);
}
Console.WriteLine();
Console.WriteLine(@"Table ""Statistics""");
foreach (var table in sqlBase.Table<Statistics>())
{
Console.WriteLine("Id: {0}\tDomain Id: {1}", table.Id, table.DomainId);
}
Console.WriteLine();
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
第一次运行后,它看起来很好。
但是在第二次运行之后,当域重复时 - sqlite 扩展插入错误的域 id
我在哪里犯错?