Setting the value of primary Key manually on Entity Model before insert - entity-framework

I have my Entity model where every entity has a primary key and they are marked with StoreGeneratedPattern = "Identity", the entity I am interested in is PEOPLE. It was created in oracle, and in another schema exists a "PEOLPE_HIST" table with it sequence. Before insert into PEOPLE I search on PEOPLE_HIST and if the person exists. I get the history information to including the ID (primary key) to insert into new PEOPLE table. I created a trigger for PEOPLE table to check if the ID is greater than or equal to 0, if it is, then I will not use the sequence and insert the Hist ID.
Is this possible?
thanks in advance

Related

Generate one Id column included in composite Primary Keys in JPA, while one Id starts from 1 when the other Id column changes

The entity A has an OneToMany relation with the entity B. I would like to use a composite primary key for the entity B, where one of the columns is the same as the the primary key of the entity A and the second column should be generated. How can the second column be started from 1 whenever the the other involving column within the composite primary key changes?
I use Oracle data bank and could not find any solution.
Thanks in advance!

How to use Entity Framework 6 to update many-to-many relationship?

Someone else asked a similar question here: How can I use EF6 to update a many to many table
I mention that up front because I couldn't get any of the solutions given to work.
I also studied the solution give on Code Project: http://www.codeproject.com/Tips/893609/CRUD-Many-to-Many-Entity-Framework, but this doesn't work for me either.
I'm trying to keep this as simple as possible.
I have two tables: dbo.Teacher and dbo.Student. Each has an "ID" column that servers as a primary key. I also have a third table called dbo.StudentTeacher which has exactly two columns, both are non-nullable and foreign keyed to the previous two tables; in other words, it establishes a many-to-many relationship between teachers and students. As expected, the EDMX designed shows only dbo.Student and dbo.Teacher and infers the relationship between them.
Here is a script for the above; there is nothing else in the database.
CREATE TABLE dbo.Teacher
(
Id INT NOT NULL PRIMARY KEY,
Name VARCHAR(MAX)
);
CREATE TABLE dbo.Student
(
Id INT NOT NULL PRIMARY KEY,
Name VARCHAR(MAX)
);
CREATE TABLE dbo.TeacherStudent
(
TeacherId INT NOT NULL FOREIGN KEY REFERENCES Teacher(Id),
StudentId INT NOT NULL FOREIGN KEY REFERENCES Student(Id)
);
INSERT INTO Teacher(Id, Name)
VALUES
(101, 'Tom');
INSERT INTO Student(Id, Name)
VALUES
(201, 'Sue'),
(202, 'Stan');
INSERT INTO TeacherStudent(TeacherId, StudentId)
VALUES
(101, 201);
Now that I've established my data structures, I want to accomplish a very simple task. From the script above, you can see that we have one teacher named "Tom" who has a student named "Sue". We also have a student named "Stan" with no teacher. My task is to modify the database so that Sue is no longer Tom's student and Stan becomes Tom's student.
To accomplish this, I wrote the following code:
class Program
{
static void Main(string[] args)
{
using (var entities = new TestEntities())
{
// There is only one teacher in the system.
Teacher teacher = entities.Teachers.Single();
// This teacher has a student #201: Sue.
// I want to replace her with student #202: Stan.
teacher.Students.Clear();
teacher.Students.Add(new Student() { Id = 202 });
entities.SaveChanges();
}
}
}
It looks very simple: clear the students associated with Tom and then add Stan as Tom's student. However, when I run the code, I get the following error: Unable to update the EntitySet 'TeacherStudent' because it has a DefiningQuery and no <DeleteFunction> element exists in the <ModificationFunctionMapping> element to support the current operation.
I tried simplifying the problem by trying to just remove Sue from being Tom's student without adding Stan, and I get the exact same error message.
As I understand, this error normally occurs when Entity Framework doesn't have enough information to do what you want it to do, but I really can't see what's missing. There are two simple tables with a join table between them and I need to be able to change which rows are related to which other rows.
I should also note that if I'm not mistaken, the change that I wish to make in this example should affect only the dbo.TeacherStudent table; the other two tables should not be touched.
Okay, after some more Google-Fu, I figured it out.
Even tho the join table must have only two columns with each column foreign keyed to the two tables to be related, the join table still needs a primary key, which can be a composite of the two foreign keys.
Thus, dbo.TeacherStudent should be created with this:
CREATE TABLE dbo.TeacherStudent
(
TeacherId INT NOT NULL FOREIGN KEY REFERENCES Teacher(Id),
StudentId INT NOT NULL FOREIGN KEY REFERENCES Student(Id),
PRIMARY KEY(TeacherId, StudentId)
);

Not able to delete value from a table that is associated with another with foreignkeyconstraint

Hi I have two table Customer and Orders.
Customer Id is primary in Customer and Foreign key in Orders.
I have done the following coding:
ForeignKeyConstraint custOrderFK = new ForeignKeyConstraint("CustOrderFK",
custDS.Tables["CustTable"].Columns["CustomerID"],
custDS.Tables["OrdersTable"].Columns["CustomerID"]);
custOrderFK.DeleteRule = Rule.None;
custDS.Tables["OrdersTable"].Constraints.Add(custOrderFK);
Since I have mentioned custOrderFK.DeleteRule = Rule.None; deleting an entry in customer's table should not affect order's table. But I am not able to delete a row from Customer table. It throws exception. I am new to ado.net.
Maybe something is wrong with my understanding of rules.
Use delete cascade option with foreign key.

Problem adding foreign key in simple setup

I have two tables
Users
Users_Role
I decided to try to add a foreign key as to my understanding it will let me cascade the delete procedure when removing a user from Users (as well as enforce integrity).
So via Management Studio I right clicked my Users_Role table, Design, then went into Relationships. I added a new relationship between the two tables as such:
Foreign Key Base Table: Users_Role
Foreign Key Columns: UserID
Primary/Unique Key Base: Users
Primary/Unique Key columns: ID
When I then try to save, I get the following error:
'Users' table saved successfully
'Users_Role' table
- Unable to create relationship 'FK_Users_Role_Users'.
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_Users_Role_Users". The conflict occurred in database "db", table "dbo.Users", column 'ID'.
I'm not sure what's going on. Adds the relationship to Users, but not Users_Role? The only thing special about Users_Role is that my primary key consists of two columns, UserID and Role (the only two columns in the table, if that matters). Otherwise, nothing special.
This error means that in your current database, you have entries in the "Users_Role" table which have a "UserID" value that is not present in the Users table as ID.
You first need to find those "rogue" rows and either update or delete them, before you can create the foreign key to enforce referential integrity and avoid such problems in the future.
You can find those by issuing this command:
SELECT * FROM Users_Role
WHERE UserID NOT IN
(SELECT DISTINCT ID FROM Users)

foreign key constraint in sql

I have 2 tables in sql server with primary keys set to identity. They are related and work fine.
I then created a form in vb 2008 and tried inserting some values into my database the respective primary keys work but the primary key in the parent table wont show up in the child table.I did create a relationship in vb using ado.net and all the details of my table are defineed in the data table. For example
cust tables (custid,name,..)
book table(bookid,bookname,..,custid)
in vb my insert statement is something like Insert into cust(name) values(#name)
insert into book(bookname) values(#bookname). I do not include the id columns as they auto generate in the database(tables).
My question is that how do i get to insert the custid in the book table when the data is stored back into the tavles in my database.
Please advice with an example as im not half as good as you guys.
Kind Regards
You have to know which customer you want to associate with the book before INSERTing the book. If you don't know before hand, you can't. So somewhere in your Form there should be a way to select a customer. Then when you create a book, you grab that customer's ID and insert it along with the other book info.
You don't actually say that you created a foreign key constraint between the two tables!
You need to:
Ensure that you create an explicit foreign key on the BOOK table to point to a customer in the CUST table.
First insert the customer.
Then find out what the customer's auto-generated ID was. That value is in ##IDENTITY. Store it somewhere e.g. #CUSTID.
Insert the book, specifying #CUSTID as the customer's ID.