带有多个外键的SQLite.Net扩展

时间:2014-08-13 15:27:07

标签: sqlite-net-extensions

尝试创建具有多值外键的一对多关系时出现以下错误...

**

SQLite.Net.SQLiteException:外键不匹配 - "活动"引用" Node"

**

这是表格SQL(为简洁起见而简化)......

CREATE TABLE [Activity] (
  [ID] INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, 
  [InstId_FK] numeric(18,0) NOT NULL, 
  [NodeSeq_FK] numeric(3,0) NOT NULL, 
  [ActivityType] int NOT NULL, 
  CONSTRAINT [Node_FK] FOREIGN KEY([InstId_FK], [NodeSeq_FK]) REFERENCES [Node]([ID], [NodeSeq])ON DELETE CASCADE);

CREATE TABLE [Node] (
  [ID] NUMERIC(18) NOT NULL CONSTRAINT [ID] REFERENCES [Trip]([ID]) ON DELETE CASCADE, 
  [NodeSeq] numeric(3,0) NOT NULL, 
  [Status] int, 
  [Name] nvarchar(30) NOT NULL, 
  CONSTRAINT [sqlite_autoindex_TripNode_1] PRIMARY KEY ([ID], [NodeSeq]));

我的C#模型(为了清晰起见再次简化)......

public class TripNodeActivity : LocationAware
{
    [PrimaryKey, AutoIncrement, ForeignKey(typeof(Node),Order = 1)]
    public int Id { get; set; }

    [Column("InstId_FK")]
    public int InstIdFk { get; set; }

    [Column("NodeSeq_FK"), ForeignKey(typeof(Node),Order = 2)]
    public int NodeSeqFk { get; set; }

    public int ActivityType { get; set; }
}

public class Node
{
    public Node(){Activity = new List<Activity>();}

    [OneToMany(CascadeOperations = CascadeOperation.All)] 
    public List<Activity> Activity{get;set;}  

    [PrimaryKey, ForeignKey(typeof(Trip))]
    public int Id { get; set; }

    [PrimaryKey]
    public int NodeSeq { get; set; }

    public int Status { get; set; }
    public String Name { get; set; }
}

尝试使用以下方法保存模型时发生此错误:

SQLiteConnection.InsertOrReplaceWithChildren(NodeFromAbove,true)

1 个答案:

答案 0 :(得分:1)

那里很少。

首先,PrimaryKey类中有两个Node属性。这在SQLite-Net中不受支持。

其次,您指定PrimaryKey也是两个类中另一个表的ForeignKey。那不是你想要做的。

可能这更有可能是你尝试的:

public class TripNodeActivity : LocationAware
{
    [PrimaryKey, AutoIncrement]
    public int Id { get; set; }

    [Column("InstId_FK")]
    public int InstIdFk { get; set; }

    [Column("NodeSeq_FK"), ForeignKey(typeof(Node)]
    public int NodeSeqFk { get; set; }

    public int ActivityType { get; set; }
}

public class Node
{
    public Node(){Activity = new List<Activity>();}

    [OneToMany(CascadeOperations = CascadeOperation.All)] 
    public List<Activity> Activity{get;set;}  

    [PrimaryKey]
    public int Id { get; set; }

    public int NodeSeq { get; set; }

    public int Status { get; set; }
    public String Name { get; set; }
}

希望它有所帮助。