无法将多个项插入SQLite数据库

时间:2015-06-30 18:40:17

标签: c# linq sqlite

数据库具有批处理数据的主表,每个批处理可以包含零个或多个样本。它们在Batch.BatchID == Samples.FK_BatchID上链接。这些表的类如下所示。

我可以为Batches添加一个值 - 自动增量BatchID按预期更新。 我可以为Samples添加一个值。 我无法向Samples表添加多个值,并使用

获取异常
  

其他信息:无法添加具有已在使用的密钥的实体。

如果我将STOP设置为'1',那么db将获得一个带有正确引用的新Sample的新Batch。我必须做什么才能为单个批次添加多个样品。另外,我最好使用相同的上下文和单个“SubmitChanges()”操作 - 但让我在跑步前走路。

以下是我尝试的代码:

 Int64 newbatchID = 0;
 using (var context = new Data.BatchContext(connection))
 {    // This 'chunk' work fine and the newbatchID gets the new value
      context.Log = Console.Out;
      Data.Batches newBatch = new Data.Batches {
           Created = System.DateTime.Now.ToString("u"),
           Title = "New Title",
           Varietal = "Waltz"
      };

      // Return the Batch Id if necessary...
      var qs = from c in context.sqlite_sequence
               where c.name == "Batches"
               select c.seq;
      context.Batches.InsertOnSubmit(newBatch);
      context.SubmitChanges();
      newbatchID = qs.ToList().First();
 }

 // Use the new batch ID to submit a load of new samples
 int STOP = 2;     // PROBLEM. If Stop is not 1 the following fails
 using (var context = new Data.BatchContext(connection))
 {
      context.Log = Console.Out;
      List<Data.Samples> samplelist = new List<Data.Samples>();
      for (var i = 0; i < STOP; ++i)
      {    // Just to get different time values
           System.Threading.Thread.Sleep(500);
           samplelist.Add(
                new Data.Samples {
                     // Commenting out the FK_BatchID doesn't help
                     FK_BatchID = newbatchID,
                     Created = System.DateTime.Now.ToString("u"),
                     ImageURI = String.Format("./Path/Img_{0}.jpg", i)
                });
           }
           context.Samples.InsertAllOnSubmit(samplelist);
           context.SubmitChanges();
      }

数据库类

[Table(Name = "Batches")]
public class Batches
{
    public virtual ICollection<Batches> batches { get; set; }
    public Batches()
    {
        batches = new HashSet<Batches>();
    }

    // Primary key - nullable to allow Autoincrement
    [Column(Name = "BatchID", IsPrimaryKey = true)]
    public Int64? BatchID { get; set; }

    // Batch creation date
    [Column(Name = "Created")]
    public String Created { get; set; }

    // Other String columns the same as Created
    ...
}

[Table(Name = "Samples")]
public class Samples
{
    public virtual ICollection<Samples> samples { get; set; }
    public Samples()
    {
        samples = new HashSet<Samples>();
    }

    // Primary key - nullable to allow Autoincrement
    [Column(Name = "SampleID", IsPrimaryKey = true)]
    public Int64? SampleID { get; set; }

    // Foreign key to the Batches Table
    private EntityRef<Batches> _batch = new EntityRef<Batches>();
    [Association(Name = "FK_BatchID", IsForeignKey = true, 
                 Storage = "_batch", ThisKey = "FK_BatchID", 
                  OtherKey = "BatchID")]
    public Batches Batches
    {
        get { return _batch.Entity; }
        set { _batch.Entity = value; }
    }
    // Foreign key table entry
    [Column(Name = "FK_BatchID")]
    public Int64? FK_BatchID { get; set; }

    // Date the image was processed by the batch
    [Column(Name = "Created")]
    public String Created { get; set; }

    // Other String columns etc
    ...
 }

编辑:

在尝试修改Column装饰(即IsDbGenerated和/或DbType等)失败后,我已经实现了使用下面显示的sqlite_sequence的工作。这用于查找各种表ID的值,然后在创建新对象时使用这些值。然后,这些都可以包含在单个交易中

 // Start by getting the latest autoincrement values
 var aiQuery = (from c in context.sqlite_sequence
                select c).ToList();

 Int64 batchId = 1 + aiQuery.Find(q => q.name == @"Batches").seq;
 Int64 sampleId = 1 + aiQuery.Find(q => q.name == @"Samples").seq;

 // Create objects etc
 ...

 // Then update the db once only
 context.Batches.InsertOnSubmit(newBatch);
 context.SubmitChanges();

如果没有更好的解决方案,那么我会接受这个作为答案

1 个答案:

答案 0 :(得分:0)

如果没有适当的解决方案,这是我的解决方法。

使用sql_sequence建立自动增量Id值,然后在正在创建的对象中显式使用。

var aiQuery = (from sequence in sqlite_sequence
               select sequence).ToList();

BatchId = 1 + aiQuery.Find(q => q.name == @"Batches").seq;
SampleId = 1 + aiQuery.Find(q => q.name == @"Samples").seq;

为方便起见,我把它放在我的类中,来自Linq.DataContext

然后,可以根据以下伪代码在单个事务中添加多个插入。

Batch batch = new Batch { id = BatchId, ... }
foreach (int i=0; i<n; ++i)
{
   batch.AddSample(new Sample { id = SampleId+i, batchid = BatchId, ... });
}

// Update db
context.Batches.InsertOnSubmit(batch);
context.SubmitChanges();