简体   繁体   English

在我的C#代码中为Sqlite添加外键

[英]Add foreign key inside my C# code for Sqlite

I have created a Sqlite database, but when I went to Xamarin.forms, I get that I have to make a class for every table inside my Sqlite database. 我已经创建了一个Sqlite数据库,但是当我进入Xamarin.forms时,我发现必须为Sqlite数据库中的每个表创建一个类。

I have 3 tables: 我有3张桌子:

  1. User with 3 columns UserID (PK), Mail (unique), Password User有3列UserID (PK), Mail (唯一的),密码
  2. Ticket with 4 columns TicketID (PK), Name , Description , TicketValue 具有4列Ticket TicketID (PK), NameDescriptionTicketValue
  3. UserTickets with 4 columns UserID (FK), TicketID (FK), TicketValue (FK) UserTickets与4列UserID (FK), TicketID (FK), TicketValue (FK)

In C# I could handle the primary key and unique using 在C#中,我可以处理主键和唯一使用

[PrimaryKey, Unique]

like this above. 像上面这样

But I don't know how to set the foreign key. 但是我不知道如何设置外键。

I am using Nuget Sqlite 我正在使用Nuget Sqlite

It's sounds like you're trying to create tables with foreign keys in SQLite. 听起来您正在尝试使用SQLite中的外键创建表。 If that's correct this should help. 如果是正确的话,应该会有所帮助。

In SQLite during table creation you can set the foreign key references at the end of your query. 在表创建过程中的SQLite中,您可以在查询结束时设置外键引用。 For example the user tickets table creation query would look like this. 例如,用户票证表创建查询将如下所示。

CREATE TABLE `UserTickets` (
`UserID`    INTEGER,
`TicketID`  INTEGER,
`TicketValue`   INTEGER,
FOREIGN KEY(`UserID`) REFERENCES `User`(`UserID`)
FOREIGN KEY(`TicketID`) REFERENCES `Ticket`(`TicketID`)
FOREIGN KEY(`TicketValue`) REFERENCES `Ticket`(`TicketValue`)
);

Now, it's important to turn foreign keys on everytime you create a connection to the database. 现在,每次创建数据库连接时都必须打开外键,这一点很重要。 SQLite won't do this for you so make sure it's specified in your connection string if you add foreign key constraints like 'ON DELETE CASCADE' SQLite不会为您执行此操作,因此,如果添加外键约束(如“ ON DELETE CASCADE”),请确保在连接字符串中指定了它

Example: 例:

 SQLiteConnection conn = new SQLiteConnection("Data Source = [Your DB Path];foreign keys=true;");

Last note: You will need to adjust the table creation query to add any increments or unique constraints. 最后说明:您将需要调整表创建查询以添加任何增量或唯一约束。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM