Im making an Order table in which paintings_id and customer_id act as foreign keys and they correspond to customers_id and painting_id which act as primary keys in their respective tables. They have the same datatype that is Int. I have searched for this error but cannot find any possible solution.
use artgallery;
CREATE TABLE item_order(
order_id INT UNIQUE NOT NULL auto_increment,
customer_id INT UNIQUE NOT NULL ,
paintings_id INT UNIQUE NOT NULL ,
primary key(order_id),
FOREIGN KEY (customer_id) REFERENCES customers(customers_id),
FOREIGN KEY(paintings_id) references pantings(painting_id)
);
I cut and pasted your create table statement as-is...and it worked fine. Your error must be generated from something other than mysql....which brings me to another point...what's the error?
....nevermind...I see your error in the subject field.....not sure...as I said it worked fine on MySQL version 5.1.
Make sure that your foreign key reference columns have the same definition as the columns in your other tables.
For example, you are adding a foreign key with this column as the reference:
customer_id INT UNIQUE NOT NULL
Which means 'customers_id' in your 'customers' table must be:
customers_id INT NOT NULL (possibly AUTO_INCREMENT)
If you define one as 'UNSIGNED' and/or 'NULL' / 'NOT NULL', the referenced column must also have those attributes. See Using Foreign Key Constraints.
Related
Like when I add the First name, Last Name, Username and Password. For some reason I cant get it to let me add entries such as the UserId to say 1, 2, 3 and so on with the rest of the information
Instead I am getting this error when I try to register another person or make another entry to GridView1:
An exception of type 'System.Data.SqlClient.SqlException' occurred in
System.Data.Linq.dll but was not handled in user code. Additional
information: Violation of PRIMARY KEY constraint
'PK__User__1788CC4C1B5B052D'. Cannot insert duplicate key
User Table
Registration
Registration website
Error Message
I might not have explained this well. Forgive me.
loggedincode
logincode
linqtosql
Debugger
1) Make the column identity: Go to column property and set Identity specification and Is Identity: make it yes and increment by value 1
OR by:
UserID INT IDENTITY(1,1) PRIMARY KEY
2) Check your ID property inside the Item class to ensure that it have attributes like this:
[Column(Storage="_ID", AutoSync=AutoSync.OnInsert,
DbType="INT NOT NULL IDENTITY", IsPrimaryKey=true, IsDbGenerated=true)]
Look at the IsDbGenerated=true, it is the important guy here.
Maybe you created the DatabaseContext using the designer before adjusting the IDENTITY on the Sql Server, so just regenerate this class (by deleting the table in the designer and dropping it from the Server Explorer again).
OR
In your LINQ to SQL designer, you need to make sure your column is set to:
Auto Generated Value = TRUE
Auto-Sync = ON INSERT
Hope this will help:)
So looks like your Key isn't auto populated.
This will cause a big issue because a primary key can't be null.
In your create table TSQL in picture "User table"
change the line to:
[UserID] INT NOT NULL
to
UserID INT IDENTITY(1,1) PRIMARY KEY
That should fix your problem
Caz
You are getting that error is because your User table's primary key column is not set to be an identity column. You are not setting the value of this column from your C# code, but the default is zero. Most likely you inserted one record successfully so a record with zero as the primary key got inserted. Now you are trying to insert more rows and another zero is going in so it is throwing that exception.
Fix
Make sure your User table's primary key is set to an indentity column so it auto increments. If you do not want it to be identity and increment automatically, then you need to pass the value in but you have to make sure it is unique or you will get the same error. I would just make it identity.
This question already has answers here:
What is the difference between Primary Key and unique key constraint?
(5 answers)
Closed 9 years ago.
My company is currently in the process of rewriting an application that we recently acquired. We chose to use ASP.net mvc4 to build this system as well as using the Entity Framework as our ORM. The previous owner of the company we acquired is very adamant that we use their old database and not change anything about it so that clients can use our product concurrently with the old system while we are developing the different modules.
I found out that the old table structures does not have a Primary key, rather, it uses a Unique Index to serve as their primary key. Now when using Entity framework I have tried to match their tables in structure but have been unable to do so as the EF generates a Primary key instead of a unique index.
When I contacted the previous owner, and explained it, he told me that "the Unique key in every table is the Primary Key. They are synonyms to each other."
I am still relatively new to database systems so I am not sure if this is correct. Can anyone clarify this?
his table when dumped to SQL generates:
-- ----------------------------
-- Indexes structure for table AT_APSRANCD
-- ----------------------------
CREATE UNIQUE INDEX [ac_key] ON [dbo].[AT_APSRANCD]
([AC_Analysis_category] ASC, [AC_ANALYSI_CODE] ASC)
WITH (IGNORE_DUP_KEY = ON)
GO
however my system generates:
-- ----------------------------
-- Primary Key structure for table AT_APSRANCD
-- ----------------------------
ALTER TABLE [dbo].[AT_APSRANCD] ADD PRIMARY KEY ([AC_Analysis_category])
GO
EDIT:
Follow up question to this is how would I go about designing the Models for this? I am only used to using the [Key] annotation which defines it as a primary key, and without it, EF will not generate that table.
so something like this:
[Table("AT_APSRANCD")]
public class Analysis
{
[Key]
public string AnalysisCode { get; set; }
public string AnalysisCategory { get; set; }
public string ShortName { get; set; }
public string LongName { get; set; }
}
From SQL UNIQUE Constraint
The UNIQUE constraint uniquely identifies each record in a database
table.
The UNIQUE and PRIMARY KEY constraints both provide a
guarantee for uniqueness for a column or set of columns.
A PRIMARY
KEY constraint automatically has a UNIQUE constraint defined on it.
Note that you can have many UNIQUE constraints per table, but only one
PRIMARY KEY constraint per table.
Also, from Create Unique Indexes
You cannot create a unique index on a single column if that column
contains NULL in more than one row. Similarly, you cannot create a
unique index on multiple columns if the combination of columns
contains NULL in more than one row. These are treated as duplicate
values for indexing purposes.
Whereas from Create Primary Keys
All columns defined within a PRIMARY KEY constraint must be defined as
NOT NULL. If nullability is not specified, all columns participating
in a PRIMARY KEY constraint have their nullability set to NOT NULL.
They're definitely different. As mentioned in other answers:
Unique key is used just to test uniqueness and nothing else
Primary key acts as an identifier of the record.
Also, what's important is that the primary key is usually the clustered index. This means that the records are physically stored in the order defined by the primary key. This has a big consequences for performance.
Also, the clustered index key (which is most often also the primary key) is automatically included in all other indexes, so getting it doesn't require a record lookup, just reading the index is enough.
To sum up, always make sure you have a primary key on your tables. Indexes have a huge impact on performance and you want to make sure you get your indexes right.
They are most certainly not the same thing.
A primary key must be unique, but that is just one of the its requirements. Another one would be that it cannot be null, which is not required of a unique constraint.
Also, while, in a way, unique constraints can be used as a poor man's primary keys, using them with IGNORE_DUP_KEY = ON is plainly wrong. That setting means that if you try to insert a duplicate, the insertion will fail silently.
Well, they are very similar but here are the differences.
Only one primary key is allowed on a table but multiple unique indexes can be added up to the maximum allowed number of indexes for the table (SQL Server = 250 (1 x clustered, 249 x non clustered) and SQL 2008 and SQL 2012 = 1000 (1 x clustered, 999 x non clustered)).
Primary keys cannot contain nullable columns but unique indexes can. Note, that only one NULL is allowed. If the index is created across multiple columns, each combination of values and NULL’s must be unique.
By default, unless you specify otherwise in the create statement and providing that a clustered index does not already exists, the primary key is created as a clustered index. Unique indexes however are created by default as non clustered indexes unless you specify otherwise and providing that a clustered index does not already exist.
Following link will really help you.just go with it
HERE
Yes, a composite and unique key, like you have here, will give you an index very much like the primary key. One of the advantages of these are that the data is contained in the index, so it does not have to do a look up in the table if you are only querying for the fields in the key.
This is also possible in Entity Framework. It would go something like this.
public class AT_APSRANCD
{
[Column(Order = 0), Key, ForeignKey("AC_Analysis_category")]
public int AC_Analysis_category{ get; set; }
[Column(Order = 1), Key, ForeignKey("AC_ANALYSI_CODE")]
public int AC_ANALYSI_CODE{ get; set; }
}
primary key not contain any null value.
but in case of unique null value can insert in table.
any number of null value can be insert
definition of primary key PRIMARY_KEY=UNIQUE+NOT_NULL
I have a table that has an auto-incrementing primary key and it also has a unique index with two other columns. The problem is that when I insert a record, it does not include the primary key as part of the Entity Keys so if I don't change the other fields in the unique index, it complains of a duplicate entry. The only way I can get it to work is if I add the primary key to the unique index, but is there another way?
Do I understand you correct if you have an unique index which include both the primary key and two other columns?
If this is true, that is a wrong way to do it. Since one of the columns is the primary key, which always will be unique, those two other columns will never matter on the unique index.
Can you post your table definition?
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.
I have two tables. Table1 has a foreign key that represents a valid primary key in another table (Table2). Now the problem is that this foreign key can sometimes can be null (it is suppose to be like that). How can I check the constraint only when the foreign key is not null?
PD> I'm currently programming in C# and I'm using SQL Server Management Studio.
In SQL Server, FK constraints work exactly as you described - they only verify NOT NULL values against the parent table. Just use a foreign key.
You could add an additional "CHECK" constraint to the table that would enable you to pass the value into a function to check the value. Just a thought...
Take a look here for an example link