How can I update my column values in a table, with the help of primary key ?
Or can I override somehow the primary key?
Primary key is unique so you cannot change it. If you want to update the values using primary key then it is possible. But you cannot update the primary key.
this question sounds like youre trying to do another insert rather than an update.
If you're doing
insert into table (col1, col2, col3) values ('primaryKeyValue', 'col2val', 'col3val')
and then you try and do the same this will fail because of the primary key constraint.
you should be doing
update table set col1 = 'newValue', col2 = 'newValue2' where 'primaryKeyValue' = 'primaryKeyValue'
Use update query :
update tablename set column1 = 'new1', column2 = 'new2', 'primaryKey' = 'newPKValue' where 'primaryKey' = 'PKValue';
just one thing to remember 'newPKValue' should not be duplicated.
Related
When i want add new model to DB
Violation of PRIMARY KEY constraint 'PK_dbo.Factors'. Cannot insert duplicate key in object 'dbo.Factors'. The duplicate key value is (1001).
The statement has been terminated.
My code :
var factor = new Factor();
factor.UserId = UserId;
Db.Factors.Add(factor);
Db.SaveChanges();
And model map:
In my design factor is must start whit 1000 and my code for this :
protected override void Seed(BreDbContext context)
{
context.Database.ExecuteSqlCommand("DBCC CHECKIDENT('Factors', RESEED, 1000);");
}
I Find solution.
Description for problem
When run below code in Migration Seed
context.Database.ExecuteSqlCommand("DBCC CHECKIDENT('Factors', RESEED, 1000);");
this code run per request and this code destroy database.
Remove this code and insert below code
protected override void Seed(BreDbContext context)
{
//context.Database.ExecuteSqlCommand("DBCC CHECKIDENT('Factors', RESEED, 1000);");
for (int i = 0; i < 999; i++)
{
context.factors.add(new factor());
}
context.savechanges();
var rang = context.factors.tolist();
context.factors.removerange(rang);
context.savechanges();
}
after create database comment all code in seed method.
best reference https://weblog.west-wind.com/posts/2013/Mar/26/Firing-an-Entity-Framework-Database-Initializer-from-within-DbContext
I think it's because u insert the value that has already in the PRIMARY KEY field which mean PRIMARY KEY value must be a unique value
For example u have a table with value :
id name
1 john
2 serah
3 crish
But after that you insert a new value:
3 victoria
in above case will throw an error because in the table already has a value with id = 3 (crish) // id field is unique (PRIMARY KEY)
OR
In other problem case if ur table has a relation with other table, if u want to insert a new value into FOREIGN KEY Table, u need to inserted first in PRIMARY KEY Table because FOREIGN KEY need to reference to PRIMARY KEY value.
I hope my answer helping u
I have the following code and I want to delete all rows from TABLE where the column 'id' IS NOT Primary Key.
#{
using (var db = new DataClassesDataContext())
{
var query = db.Table.Where(r => r.id == 2).ToList();
if (query != null)
{
foreach (var q in query)
{
db.Table.DeleteOnSubmit(q);
}
}
db.SubmitChanges();
}}
This throws a System.InvalidOperationException because the table has not Primary Key column.
How is it possible to do that without adding a primary key in the SQL Server database?
Thanks in advance
Open the LINQ Designer. Open the properties window for the table you want to delete a record from. Click on any of the columns in the entity you want to delete and you'll see a property labeled "Primary Key". Change the value to true for column you want to use as a primary key.
P/S:This will not set the primary key on your real table.
I have the following table in SQL server
projects
id(PK, int, not null)
name (varchar(255), not null)
public_key_token (varchar(50), null)
I have added a unique constraint to the name column using
ALTER TABLE dbo.projects
ADD CONSTRAINT name_unique UNIQUE (name);
which results in a Unique, Non-Clustered index on the table (trusting SSMS).
In the code I'm retrieving the table data using
using (SqlDataAdapter adapter = new SqlDataAdapter("select * from " + DbTabName, con))
{
using (DataTable table = new DataTable(DbTabName))
{
DataTable dt = adapter.FillSchema(table, SchemaType.Source);
PkColumns = dt.PrimaryKey.Select(c => c.ColumnName).ToList();
AutoIncrementColumns = dt.PrimaryKey.Where(c => c.AutoIncrement).Select(c => c.ColumnName).ToList();
UniqueColumns = dt.Columns.Cast<DataColumn>().Where(c => c.Unique).Select(c => c.ColumnName).ToList();
...
}
}
The PKs and AutoIncrement columns are OK but in UniqueColumns I only get the PK column again.
The name column arrives in C# without the Unique constraint.
Changing the SchemaType to Mapped did not alter the result.
Why do I lose this constraint on the way to C#? Am I missing something on the SQL Server side or in C#?
[UPDATE]
#Tim-Schmelter's answer only solves the problem half way.
Just adding the index did not work. Also adding the index when the PK on the id column exists doesn't work.
The only way I got it to work was delete the table, recreate it without any key and indexes and then add the unique index as in Tim's answer. However, after adding the PK for the id column once more I'm back to the old behaviour that only the id is listed as unique column.
This is really weird.
Use this to create a unique index or use the the gui of SSMS.
CREATE UNIQUE NONCLUSTERED INDEX [name_unique] ON [dbo].[projects]
(
name ASC
)
You have added a unique constraint not a unique index.
Your code now successfully retrieves the UniqueColumns(the single column name).
i am creating a custom CustomerID by getting the first double characters of first name and last name taken from textboxes as following:
string CustomID = (FirstNameTxtbox.Value.Substring(0, 2) + LastNametxtbox.Value.Substring(0, 2));
in order to avoid a Duplicated CustomerID
i am trying to:
get the 5th value which is the int since the first 4 values are characters. and then increase it by 1.
my attempt:
string s = cmd.CommandText= " Select MAX(CustomerID) from Customers";
string CustomID = (FirstNameTxtbox.Value.Substring(0, 2) + LastNametxtbox.Value.Substring(0, 2) + (Convert.ToInt32(s)+1)) ;
example:
First name= Mak
last name = shima
CustomerID = MASH1
next value will be e.g KAAR2
Your practice is not recommended, you should design a primary key with Auto Increment small value like integer, remember that the table is physically sorted on the clustered index (your primary key), and your non-clustered indexes are keyed based on your primary key.
You can add your combined value in another field if you still need it, and if your queries are based on it, create a non clustered index for it.
Make the primary key an auto increment integer and the CustomerID is a string that is computed based on the ID, this way it will never duplicate.
You can set the CustomerID by:
Computed Field based on the auto increment ID
Trigger that fires on insert and set the CustomerID
Custom Code in your back-end, add the customer object, retrieve the primary key and set the CustomerID
Your CustomerID can be something like 0000001.
ex: First customer will have a primary key of 1, the CustomerID will be 000001, next customer will be 000002 and so on.
Yes Primary key (id) is necessary but Customer ID can be Custom String like 'anything'.
I you want to generate Customer ID like this
*First name= Mak
last name = shima
CustomerID = MASH1
next value will be e.g KAAR2*
Use front end to generate KA(first)AR(last)+Sequence in Sql Server /Oracle.
CREATE SEQUENCE [dbo].[CustomerId_Generation]
AS [bigint]
START WITH 1
INCREMENT BY 1
MINVALUE -9223372036854775808
MAXVALUE 9223372036854775807
CACHE
GO
Get value of sequence and Add to database afterward.
There was a case that Same CutomerID for returning customer than i mean repetitive same CutomerID can also be handled by your code if you follow this approach.
I have two tables with foreign key relationship (1 to many). How can I do that when I'll remove item from first table, it will delete automatically all values with it's foreign key from second table?
So when I'll remove item from 1 table it will remove all items from 2 table whih NameId = ID of 1 table
Depends on the database management system; with MS SQL Server, you can set a foreign key to "ON DELETE CASCADE" which does exactly what you're asking for.
http://www.techonthenet.com/sql_server/foreign_keys/foreign_delete.php
You could just write a function for that:
public void RemoveWithRelatedEntries(int table1ItemID)
{
using(var db = new dbEntities())
{
// get all entities of table 2
var tab2Entities = db.table2.Where(tab2Ent=>tab2Ent.table1Reference == table1ItemID);
// remove all those entities
foreach(table2Item item in tab2Entities)
{
db.table2.Remove(item);
}
// finally remove entity from table 1
var table1entitiy = db.table1.Find(table1ItemID);
db.table1.Remove(table1entity);
db.Save();
}
}
there are probably more elegant solutions but this was what came first to my mind.