简体   繁体   中英

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.

I have 3 tables:

  1. User with 3 columns UserID (PK), Mail (unique), Password
  2. Ticket with 4 columns TicketID (PK), Name , Description , TicketValue
  3. UserTickets with 4 columns UserID (FK), TicketID (FK), TicketValue (FK)

In C# I could handle the primary key and unique using

[PrimaryKey, Unique]

like this above.

But I don't know how to set the foreign key.

I am using Nuget Sqlite

It's sounds like you're trying to create tables with foreign keys in 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. 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'

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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