How to 'add caused_By in ComboBox' in Visual Studio - c#

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.

Related

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:
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.

Asp.Net Core Entity Framework Migration Error: index needed in a foreign key constraint [duplicate]

I need to ALTER my existing database to add a column. Consequently I also want to update the UNIQUE field to encompass that new column. I'm trying to remove the current index but keep getting the error MySQL Cannot drop index needed in a foreign key constraint
CREATE TABLE mytable_a (
ID TINYINT NOT NULL AUTO_INCREMENT PRIMARY KEY,
Name VARCHAR(255) NOT NULL,
UNIQUE(Name)
) ENGINE=InnoDB;
CREATE TABLE mytable_b (
ID TINYINT NOT NULL AUTO_INCREMENT PRIMARY KEY,
Name VARCHAR(255) NOT NULL,
UNIQUE(Name)
) ENGINE=InnoDB;
CREATE TABLE mytable_c (
ID TINYINT NOT NULL AUTO_INCREMENT PRIMARY KEY,
Name VARCHAR(255) NOT NULL,
UNIQUE(Name)
) ENGINE=InnoDB;
CREATE TABLE `mytable` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`AID` tinyint(5) NOT NULL,
`BID` tinyint(5) NOT NULL,
`CID` tinyint(5) NOT NULL,
PRIMARY KEY (`ID`),
UNIQUE KEY `AID` (`AID`,`BID`,`CID`),
KEY `BID` (`BID`),
KEY `CID` (`CID`),
CONSTRAINT `mytable_ibfk_1` FOREIGN KEY (`AID`) REFERENCES `mytable_a` (`ID`) ON DELETE CASCADE,
CONSTRAINT `mytable_ibfk_2` FOREIGN KEY (`BID`) REFERENCES `mytable_b` (`ID`) ON DELETE CASCADE,
CONSTRAINT `mytable_ibfk_3` FOREIGN KEY (`CID`) REFERENCES `mytable_c` (`ID`) ON DELETE CASCADE
) ENGINE=InnoDB;
mysql> ALTER TABLE mytable DROP INDEX AID;
ERROR 1553 (HY000): Cannot drop index 'AID': needed in a foreign key constraint
You have to drop the foreign key. Foreign keys in MySQL automatically create an index on the table (There was a SO Question on the topic).
ALTER TABLE mytable DROP FOREIGN KEY mytable_ibfk_1 ;
Step 1
List foreign key ( NOTE that its different from index name )
SHOW CREATE TABLE <Table Name>
The result will show you the foreign key name.
Format:
CONSTRAINT `FOREIGN_KEY_NAME` FOREIGN KEY (`FOREIGN_KEY_COLUMN`) REFERENCES `FOREIGN_KEY_TABLE` (`id`),
Step 2
Drop (Foreign/primary/key) Key
ALTER TABLE <Table Name> DROP FOREIGN KEY <Foreign key name>
Step 3
Drop the index.
If you mean that you can do this:
CREATE TABLE mytable_d (
ID TINYINT NOT NULL AUTO_INCREMENT PRIMARY KEY,
Name VARCHAR(255) NOT NULL,
UNIQUE(Name)
) ENGINE=InnoDB;
ALTER TABLE mytable
ADD COLUMN DID tinyint(5) NOT NULL,
ADD CONSTRAINT mytable_ibfk_4
FOREIGN KEY (DID)
REFERENCES mytable_d (ID) ON DELETE CASCADE;
> OK.
But then:
ALTER TABLE mytable
DROP KEY AID ;
gives error.
You can drop the index and create a new one in one ALTER TABLE statement:
ALTER TABLE mytable
DROP KEY AID ,
ADD UNIQUE KEY AID (AID, BID, CID, DID);
A foreign key always requires an index. Without an index enforcing the constraint would require a full table scan on the referenced table for every inserted or updated key in the referencing table. And that would have an unacceptable performance impact.
This has the following 2 consequences:
When creating a foreign key, the database checks if an index exists. If not an index will be created. By default, it will have the same name as the constraint.
When there is only one index that can be used for the foreign key, it can't be dropped. If you really wan't to drop it, you either have to drop the foreign key constraint or to create another index for it first.
Because you have to have an index on a foreign key field you can just create a simple index on the field 'AID'
CREATE INDEX aid_index ON mytable (AID);
and only then drop the unique index 'AID'
ALTER TABLE mytable DROP INDEX AID;
I think this is easy way to drop the index.
set FOREIGN_KEY_CHECKS=0; //disable checks
ALTER TABLE mytable DROP INDEX AID;
set FOREIGN_KEY_CHECKS=1; //enable checks
drop the index and the foreign_key in the same query like below
ALTER TABLE `your_table_name` DROP FOREIGN KEY `your_index`;
ALTER TABLE `your_table_name` DROP COLUMN `your_foreign_key_id`;
Dropping FK is tedious and risky. Simply create the new index with new columns and new index name, such as AID2. After the new Unique Index is created, you can drop the old one with no issue. Or you can use the solution given above to incorporate the "drop index, add unique index" in the same alter table command. Both solutions will work
In my case I dropped the foreign key and I still could not drop the index. That was because there was yet another table that had a foreign key to this table on the same fields. After I dropped the foreign key on the other table I could drop the indexes on this table.
If you are using PhpMyAdmin sometimes it don't show the foreign key to delete.
The error code gives us the name of the foreign key and the table where it was defined, so the code is:
ALTER TABLE your_table DROP FOREIGN KEY foreign_key_name;
You can show Relation view in phpMyAdmin and first delete foreign key. After this you can remove index.
You can easily check it with DBeaver. Example:
As you can see there are 3 FKs but only 2 FK indexes. There is no index for FK_benefCompanyNumber_beneficiaries_benefId as UK index provide uniqueness for that FK.
To drop that UK you need to:
DROP FK_benefCompanyNumber_beneficiaries_benefId
DROP UK
CREATE FK_benefCompanyNumber_beneficiaries_benefId
The current most upvoted answer is not complete.
One needs to remove all the foreign keys whose "source" column is also present in the UNIQUE KEY declaration.
So in this case, it is not enough to remove mytable_ibfk_1 for the error to go away, mytable_ibfk_2 and mytable_ibfk_3 must be deleted as well.
This is the complete answer:
ALTER TABLE mytable DROP FOREIGN KEY mytable_ibfk_1;
ALTER TABLE mytable DROP FOREIGN KEY mytable_ibfk_2;
ALTER TABLE mytable DROP FOREIGN KEY mytable_ibfk_3;
Its late now but I found a solution which might help somebody in future.
Just go to table's structure and drop foreign key from foreign keys list. Now you will be able to delete that column.

empID increment on Add emp [duplicate]

How do I auto increment the primary key in a SQL Server database table? I've had a look through the forum but can't see how to do this.
I've looked at the properties but can't see an option. I saw an answer where you go to the Identity specification property and set it to yes and set the Identity increment to 1, but that section is grayed out and I can't change the no to yes.
There must be a simple way to do this but I can't find it.
Make sure that the Key column's datatype is int and then setting identity manually, as image shows
Or just run this code
-- ID is the name of the [to be] identity column
ALTER TABLE [yourTable] DROP COLUMN ID
ALTER TABLE [yourTable] ADD ID INT IDENTITY(1,1)
the code will run, if ID is not the only column in the table
image reference fifo's
When you're creating the table, you can create an IDENTITY column as follows:
CREATE TABLE (
ID_column INT NOT NULL IDENTITY(1,1) PRIMARY KEY,
...
);
The IDENTITY property will auto-increment the column up from number 1. (Note that the data type of the column has to be an integer.) If you want to add this to an existing column, use an ALTER TABLE command.
Edit:
Tested a bit, and I can't find a way to change the Identity properties via the Column Properties window for various tables. I guess if you want to make a column an identity column, you HAVE to use an ALTER TABLE command.
You have to expand the Identity section to expose increment and seed.
Edit: I assumed that you'd have an integer datatype, not char(10). Which is reasonable I'd say and valid when I posted this answer
Expand your database, expand your table right click on your table and select design from dropdown.
Now go Column properties below of it scroll down and find Identity Specification, expand it and you will find Is Identity make it Yes. Now choose Identity Increment right below of it give the value you want to increment in it.
CREATE TABLE Persons (
Personid int IDENTITY(1,1) PRIMARY KEY,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int
);
The MS SQL Server uses the IDENTITY keyword to perform an auto-increment feature.
In the example above, the starting value for IDENTITY is 1, and it will increment by 1 for each new record.
Tip: To specify that the "Personid" column should start at value 10 and increment by 5, change it to IDENTITY(10,5).
To insert a new record into the "Persons" table, we will NOT have to specify a value for the "Personid" column (a unique value will be added automatically):
Perhaps I'm missing something but why doesn't this work with the SEQUENCE object? Is this not what you're looking for?
Example:
CREATE SCHEMA blah.
GO
CREATE SEQUENCE blah.blahsequence
START WITH 1
INCREMENT BY 1
NO CYCLE;
CREATE TABLE blah.de_blah_blah
(numbers bigint PRIMARY KEY NOT NULL
......etc
When referencing the squence in say an INSERT command just use:
NEXT VALUE FOR blah.blahsequence
More information and options for SEQUENCE
When you're using Data Type: int you can select the row which you want to get autoincremented and go to the column properties tag. There you can set the identity to 'yes'. The starting value for autoincrement can also be edited there. Hope I could help ;)
I had this issue where I had already created the table and could not change it without dropping the table so what I did was:
(Not sure when they implemented this but had it in SQL 2016)
Right click on the table in the Object Explorer:
Script Table as > DROP And CREATE To > New Query Editor Window
Then do the edit to the script said by Josien; scroll to the bottom where the CREATE TABLE is, find your Primary Key and append IDENTITY(1,1) to the end before the comma. Run script.
The DROP and CREATE script was also helpful for me because of this issue. (Which the generated script handles.)
You can use the keyword IDENTITY as the data type to the column along with PRIMARY KEY constraint when creating the table.
ex:
StudentNumber IDENTITY(1,1) PRIMARY KEY
In here the first '1' means the starting value and the second '1' is the incrementing value.
If the table is already populated it is not possible to change a column to IDENTITY column or convert it to non IDENTITY column. You would need to export all the data out then you can change column type to IDENTITY or vice versa and then import data back.
I know it is painful process but I believe there is no alternative except for using sequence as mentioned in this post.
Be carefull like if you want the ID elements to be contigius or not. As SQLSERVER ID can jump by 1000 .
Examle: before restart ID=11
after restart , you insert new row in the table, then the id will be 1012.
You could do the following: New Table Creation:
-- create new table with Column ID which is Primary Key and Auto Increment --
CREATE TABLE titles(
id INT NOT NULL IDENTITY(1,1) PRIMARY KEY, --Primary Key with Auto-Increment --
keyword VARCHAR(260),
status VARCHAR(10),
);
If you Table Already exists and need to make the changes to ID column to be auto-increment and Primary key, then see below:
ALTER TABLE table DROP COLUMN id; // drop the existing ID in the table
ALTER TABLE table ADD id int IDENTITY(1, 1) NOT NULL; // add new column ID with auto-increment
ALTER TABLE table ADD CONSTRAINT PK_ident_test PRIMARY KEY CLUSTERED (id); // make it primary key

Entity Framework “Update model from Database, table becomes relation

I'm trying to create a table from within visual studio and update my .edmx file inside Visual Studio by right-clicking the file and selecting Update Model from Database.
My table looks like this:
CREATE TABLE [dbo].[tableName] (
[UserId] UNIQUEIDENTIFIER NOT NULL,
[CategoryId] INT NOT NULL,
CONSTRAINT [PK_responsibleUser] PRIMARY KEY NONCLUSTERED ([UserId], [pkID] ASC),
CONSTRAINT [FK_responsibleUser_user] FOREIGN KEY ([UserId]) REFERENCES [dbo].[users] ([UserId]) ON DELETE CASCADE,
CONSTRAINT [FK_categoryResponsibleUser_category] FOREIGN KEY ([CategoryId]) REFERENCES [dbo].[categories] ([CategoryId]) ON DELETE CASCADE
);
This table contains two foreign keys to the tables i want to link. After I run the script "Update Model from Database", a relation between the two tables pops up.
Now Heres the problem: I need EF to generate an instance of my class in Visual studio like this:
public virtual DbSet<tableName> TableIWantToBeGeneratedByEF { get; set; }
As I said, with the current mapping it just creates a relation between two tables. How do I alter my query when creating the table for this to happen? Can this be achieved while using two foreign keys as the primary key or what?
Just open the model designed, select all (ctrl + A), press 'delete' button to delete them, and finally right click and select Update Model from Database. This will force EF to re-generate all model.
(Or just delete all referenced tables so that they are also regenerated)
Almost forgot. It seems that it was the compound primary keys that caused the problem. I changed so both my foreign keys just acted like foreign keys and not as a combined primary key, then created a columnn named Id instead with datatype INT Identity.
Ran the script "Update Model from Database" in .edmx designer and boom, there it was.

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