Add foreign key inside my C# code for Sqlite - c#

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:
User with 3 columns UserID (PK), Mail (unique), Password
Ticket with 4 columns TicketID (PK), Name, Description, TicketValue
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.

Related

How to 'add caused_By in ComboBox' in Visual Studio

I have created a database. In the Database, I have created a table called "Diseases". In Table, there is some column Name. I want to display 'bacteria, virus and protozoa' in a comboBox in visual.
create table Diseases
( DiseasesID int primary key identity,
Disease_Name varchar(80),
Caused_by varchar(80) check(caused_by IN('bacteria','virus','protozoa')),
PatientID int
foreign key (patientID) references patient
);
There's not a way that I know of to reference the possible values of an IN constraint in a query. Rather than hard-coding the possible values into a constraint, create a "lookup table" and create a foreign key from Diseases to the lookup table. Then you can use the lookup table as the source for the combo box.

Getting Foreign Keys in SQLite Database

I am trying to read in table schemas from an existing database.
I am reading in all of the tables and columns on each table using the .tables and .columns command. The .columns command returns a variable PRIMARY_KEY which lets me know it is a primary key for the table.
My question is how do I know whether a column is a foreign key to another table (and which table it is a foreign key of)?
To get information about the foreign key constraints of a table, use PRAGMA foreign_key_list.

How to update primary key value in entity framework?

I have table(and also entity in Entity Data Model) Person with following fields:
Name Type
SocialID String
FirstName String
LastName String
which SocialID is Primary Key. I want to update value of SocialID for each record. However when i try to update this field in Entity Framework I get following error:
The property 'SocialID' is part of the object's key information and cannot
be modified.
The code that i get above error is:
foreach (var p in Entity.Persons)
{
p.SocialID= p.SocialID + "00";
Entity.SaveChanges();
}
How I can do this??
As mentioned by the others, you can't do it in code. You will have to make your update in SQL. Either in a migration or directly in SQL Server Management Studio (or the equivalent if you're using a different database).
UPDATE Person -- Or 'Persons' if that's what your table is called
SET SocialID = SocialID + '00'
It will require a lot more work than this if you have other tables use this column as a foreign key (you'll have to drop the constraints first -- on all tables that reference your primary key -- then fix the data and recreate the constraints). Or as Moe said in the comments, you can set your foreign keys to cascade on update.
As per my knowledge primary key once generated cant be updated programatically,that defies the purpose of primary key.
It'll be better if you insert all your data again with new primary keys and delete old data.
Why would you want to change the primary key? Entity framework will be using that field to identify the object, you can't change its value while it is the primary key.
Based on the first answer I suggest you change the table Person to have its own primary key, let's say PersonID and mantain the SocialID as a foreign key to the Social table. If you need a person to have several Social records you may need to create other table to correspond the PersonId to several SocialId, removing the SocialId from the person table.

Deleting multiple tables from SQL Server 2008 using Datalist C#

This may seem a common question but I googled to find the right answer that can fix my problem and failed to do so.
I have multiple tables connected to each other by ProductID and I wish to delete all data from them when the product from main table has been deleted. i.e.
Products : ProductID - Vender - Description
ProductRatings : ProductID - Rating - VisitorsCount
ProductComments : ProductID - VisitorName - Comment
I read that for such situation a SQL trigger is used but I have no idea about it besides I might be mentioning my DataSource in ASCX.CS file in some cases and in some cases I might simply use SqlDatasoruce in ASCX file. Is there any query or stored procedure that can be used?
The easiest way to do this is to implement a foreign key relationship to ProductID and set on delete cascade. This is a general idea:
create table ProductRatings
(
ProductID int not null
foreign key references Products(ProductID) on delete cascade,
Rating int not null,
VisitorsCount int not null
)
What that does is when you delete a primary key value from the Products table, that causes SQL Server to delete all records that have a foreign key constraint to that primary key value. If you do this with your ProductComments table as well, problem solved. No need to explicitly call a DELETE on any records in the referencing tables.
And if you aren't using referential integrity...you should.
EDIT: this also holds true for UPDATEs on the primary key. You just need to specify on update cascade, and the foreign key references will update as the primary key did to ensure RI.

Easy way to add an ID column when there is data present

Is there an easy way to add an ID (Identity(1,1) & PK) column to a table that already has data?
I have picked up a project that was freelanced out to a horrible developer that didn't put a PK, index or anything on the tables he made.
Now that I am LINQ-ifying it, I have no PK to insert or update off of.
ALTER TABLE MyTable ADD id INT IDENTITY(1,1) PRIMARY KEY CLUSTERED
I'd be tempted to do it in three stages -
Create a new table with all the same
columns, plus you primary key column
(script out the table and then alter
it to add a PK field)
Insert into the new table all of the
values from the old table
Once your happy with it, delete the
old table and rename your new one
with the Primary Key the same as the
old table.
Open up SQL Server Management Studio
Right click the table
Click Modify
Add the Column
Set the Properties ((Is Identity) Yes, Identity Seed 1, Identity Increment 1)
Right click the Column
Click Set Primary Key
Ctrl-S

Categories