I am cloning database table in postgresql using c#.now I also want to add constraints to newly created table.
can anyone suggest way to add constraints dynamically?
I want to add all constraints from table I've clone
thanks
Use something like:
SELECT pg_get_constraintdef(oid)
FROM pg_constraint
WHERE conrelid = (select oid from pg_class where relname = ?)
where ? is the table name you are copying the constraints from. You will then get a list of check, unique, and key constraints and you can decide what to copy in your application. These are in definition form so you will see rows like:
PRIMARY KEY(id)
and
FOREIGN KEY (other_id) REFERENCES other_table (id)
Related
I am working on an existing table where as I can see there are 3(!) primary keys:
I want to copy the existing rows, alter the ctid column and then copy them again to the end of the table. I try that and I am getting the error:
Cannot add an entity with a key that is already in use.
Probably because I am copying the rows and adding them with the same primary keys. How I can solve this? Is it possible to solve it without modifying the db schema (I am thinking of adding ctid as primary key also)?
Code
var testsDefault = (from i in dc.TestUnits
where i.ctid == null
select i).ToList();
List<DAL.TestUnit> TestList = new List<DAL.TestUnit>();
foreach (var test in testsDefault)
{
DAL.TestUnit newTest = new DAL.TestUnit();
newTest.TestID = test.TestID;
newTest.PatientType = test.PatientType;
newTest.Unit = test.Unit;
newTest.ctid = "105";
TestList.Add(newTest);
}
dc.TestUnits.InsertAllOnSubmit(TestList);
dc.SubmitChanges();
You need to add ctid to your composite primary key.
ALTER TABLE TestUnits
DROP CONSTRAINT PK_WhateverYourCompositeIndexNameIs
ALTER TABLE TestUnits
ADD CONSTRAINT PK_WhateverYourCompositeIndexNameIs PRIMARY KEY (TestID, PatientType, Unit, ctid)
See: How can I alter a primary key constraint using SQL syntax?
No,it is not possible what you are trying to do without modifying the db schema. Since you are using three PK and Primary key can not be duplicate as you are trying to do. The solution to your problem is make all the row's columns unique and then add the another row but make sure all tuples must have unique entries.
The another solution to your problem is already given by Rafalon
I need some functionality in my project and I don't know if its possible.
Here is a pic with the relations:
I need to update the keys relation table LessonByFacultyMember and the same keys in Scheduling table.
I mean the keys LessonNumber,LessonCoursenumber,FacultyMemberId (LessonByFacultyMember table)
and LessonNumber,CourseNumber,FacultyMemberId (Scheduling Table).
Is it possible to update this kind of relations?
UPDATE:
I just want to be clear that i mean the possibility to change the VALUE that stored in the keys dynamically in some method.
Yes you can do so by selecting Update Cascade option in Foreign key in the database.This options automatically updates the key values in the other tables. But in your case this is not needed. The table LessonByFacultyMember should have a column LessonByFacultyMemberId as a primary key and that should be in the Scheduling table as a Reference instead of putting all the three columns in the Scheduling table. If you do so ,you don't need to worry about the updating LessonNumber,CourseNumber,FacultyMemberId in the Scheduling Table. Also in your Scheduling table there should be a column SchedulingID as a Primary Key. You can take LessonByFacultyMemberId ,SchedulingID as an auto incremented integer. Also there is no need to make LessonNumber,CourseNumber,FacultyMemberId as a Primary key in the LessonByFacultyMember table. Instead you need to make them as unique key. Similarly in Scheduling table make the current primary key as unique key and have SchedulingId as primary key. In case of showing records you need to make select statement using joins and it is better to create a view for such statement. In case if still it is not clear , create a sqlFiddle on http://sqlfiddle.com/ for your schema and share that in your question or comment to this answer. I will update the same.
I have the following table:
create table tbl
(
id int identity(1,1),
val varchar(100)
)
Now when i use Entity Framework to map objects to this table, it works, however when i change the table definition as follows:
create table tbl1
(
id int,
val varchar(100)
)
Entity Framework does not maps objects to this table. Any clue as to why is this happening would be appreciated.
Entity Framework requires a Primary Key to generate a model from the database. If there is no Primary Key on a table it will simply select the non-nullable columns as a concatenated primary key and the Entity will be read/only.
In your first table identity definition makes your id column non-nullable so you were able to create an Entity. You should have seen this message while adding that table:
"The table/view 'tbl1' does not have a primary key defined. The key
has been inferred and the definition was created as a read-only
table/view."
In your second table however there is no non-nullable column and EF cannot create an Entity for it. See the message when you try to add it:
"The table/view 'tbl1' does not have a primary key defined and no
valid primary key could be inferred. This table/view has been
excluded. To use the entity, you will need to review your schema, add
the correct keys, and uncomment it."
Entity frameworks generally need a way to distinguish between two records in a table and so require a ID/Key discriminator which need not be a primary key constraint or a unique key constraint or an identity at the DB layer. But this discriminator, a column or a set of columns, should help the entity framework identify a record uniquely and distinguish it from other records. So, you need to define such a discriminator in your entity class at the C# layer.
I need to implement an import export module for three database tables which are internally related with primary key/foreign key constraints.
I can do both part easily using c#/linq to xml/linq to sql. Problem is, when i am importing the exported data, in database, primary key tables' id are regenerating without taking/assign the id from xml file(its natural for auto increment). For this, other tables data can't be imported/showing error that primary key constraint violates.
My goal is to import all data and keep the primary/foreign key intact.
Now, can anyone please suggest me what I can do to solve this issue please? Thanks in advance.
You can use identity insert to specify a value for identity columns.
If you specify explicit values for identity columns, you yourself are responsible for resolving conflicts. If the database already has a row with id = 1, you have to decide what to do if the import also contains id = 1: SQL Server will just throw an error.
We always used BCP operations for such tasks.
I would suggest to not make your autoincrement the primary key but to have a separate primary key which can be defined somehow else... then you won't have the problem with the autoincrement
If you don't need the ids in the XML and SQL to match (only the relationships) you could use SCOPE_IDENTITY() and maintain mapping from XML ids to SQL ids to insert properly foreign key columns in other tables.
I am working with PostgreSql DB using Entity Framework:
When I add new item into DB it generates strange code:
INSERT INTO (SELECT "person_contact"."person_id" AS "person_id",
"person_contact"."contact_id" AS "contact_id"
FROM "public"."person_contact" AS "person_contact")
("person_id","contact_id")
VALUES (cast(141792 as int8),cast(289406040 as int8))
So it add
SELECT "person_contact"."person_id" AS "person_id",
"person_contact"."contact_id" AS "contact_id"
FROM "public"."person_contact" AS "person_contact"
instead of table name "public"."person_contact"
How to resolve this Entity Framework bug ???
UPD: Same issue when I try to delete "person_contact" entry. In delete statement instead of table name - select query.
There are several ways to try and fix this:
Firstly, it could be that your model has become corrupt. You could try deleting the model and recreating it. Also see my answer to this question: SQL Server foreign keys messing with entity framework model
Secondly, you say that it only happens with this table. Is there anything special about this table.
Thirdly, you could try a different .net connector for ProgressSQL, see: http://www.devart.com/dotconnect/entityframework.html
These are listed in the order that I would try them.
Most likely you forgot to create primary key on this table.
I've had the same problem and the solution in my case was very simple. The problem was that I had a column named "id", but I forgot to make it Primary Key. The moment I set it as Primary Key everything was OK.
It is very strange, because EF, normaly won't import table without primary key, but when you have column named "id" it assumes that it is a primary key.
The structure of my table was:
*DROP TABLE IF EXISTS "public"."fact_season_tickets";
CREATE TABLE "public"."fact_season_tickets" (
"id" int8 DEFAULT nextval('fact_season_tickets_id_seq'::regclass) NOT NULL,
"season_ticket_id" int8 NOT NULL,
"date_key" int4 NOT NULL,
"station_id" int4 NOT NULL,
"amount" numeric(18,2) DEFAULT 0 NOT NULL,
"status" int4 NOT NULL
)
WITH (OIDS=FALSE)*
The generated by NpgSql INSERT statement was:
*INSERT INTO (SELECT "fact_season_tickets"."id",
"fact_season_tickets"."season_ticket_id",+
"fact_season_tickets"."date_key",
"fact_season_tickets"."station_id",
"fact_season_tickets"."amount",
"fact_season_tickets"."status"
FROM "public"."fact_season_tickets" AS "fact_season_tickets")
("season_ticket_id","date_key","station_id","amount","status")
VALUES (510::int8,20150630,2,18.00::numeric,1)
RETURNING "id"*
The solution was just creating a primary key:
*ALTER TABLE "public"."fact_season_tickets" ADD PRIMARY KEY ("id");*