MS SQL Server 2008 Check Constraint, and LINQ-To-SQL - linq-to-sql

This is a tough question to word...so bear with me.
I have two tables in my database, [Item] and [AssignedProperty]. [AssignedProperty] is the child in a parent-child relationship with [Item]. So it basically just has an ItemID field and a foreign key relationship utilizing it. [AssignedProperty] also has an identical relationship with another table named [Property], and its own primary key, AssignedPropertyID. This creates a nice many-to-many relationship. I have a constraint however, that dictates that one [AssignedProperty] cannot have duplicate occurrences of ItemID and PropertyID in the same record. Therefore an [Item] can only have one of each [Property].
This works nicely, but with LINQ-To-SQL, theres an issue in what I think is the order of execution that conflicts with this constraint.
To produce this error, I load up an [Item] in my application using LINQ-To-SQL. I then select an [AssignedProperty] object, from the item's [AssignedProperties] collection and delete it. I then create a new [AssignedProperty] object with the exact same ItemID and PropertyID as the one I just deleted, and add it back to the collection. When I call [SubmitChanges] on the DataContext, it will flag me on the constraint. If the old [AssignedProperty] record was deleted first, then there is no reason why the new one should produce that error. It looks like it's attempting to insert the new [AssignedProperty] before deleting the old one.
How should I fix this, and in the database or my app? TIA

The 94% is bugging me, and the answer is actually in the comments of the original post.
So, this is just so I can actually select an answer.

Related

PowerApps: Access-like update query

I’m pretty new to PowerApps and need to migrate an Access database over to PowerApps, first of all it’s tables to Dataverse. It’s a typical use case for a model-driven app, with many relationships between the tables. All Access tables had an autogenerated ID field as their primary key.
I transferred all tables via Excel ex/import to Dataverse. Before importing,I renamed all ID fields (columns) to ID_old and let Dataverse create its own, autogenerated ID field for each table.
What I want to achieve is to re-establish all relationships between the tables, where the foreign key points to the new primary key provided by Dataverse, as I want to avoid double keys. As a first step I created relationships between the ID_old field and the corresponding (old) foreign key field in the related table.
In good old Access, I’d now simply run an update query, filling the new (yet empty) foreign key field with the new ID of the related table. Finally, I would change the relationship to the new primary and foreign keys and then delete the old ID fields.
Where I got stuck is the update query. I searched the net and found a couple of options like UpdateIf / Patch functions or Power Query or Excel ex/import and some more. They all read pretty complicated and time intensive and I think I must have overseen a very simple solution for such a pretty common problem.
Is there someone out there who might point me in the right (and simple) direction? Thanks!
A more efficient approach would be to start with creating extra ID columns in Access. Generate your GUIDs and fix your foreign keys there. This can be done efficiently using a few SQL update statements.
When it comes to transferring your Access tables to Dataverse you just provide your Access shadow primary keys in the Create message.
I solved the issue as follows, which is pretty efficient in my perception. I”m assuming you have a auto-numbered ID field in every Access table, which you used for your relationships
Export your tables from Access to Excel.
Rename your ID fields to ID_old in all tables using Excel, as well as your foreign key fields to e.g. ForeignKey_old. This will make it easy to identify the fields later in Dataverse.
Import into Dataverse, using the Power Query tool. Important: Make sure, that you choose ID_old as additional primary key field in the last import step.
Re-create all relationships in Dataverse, using the Lookup datatype. This will create a new, yet empty column in your table.
Now use the “Edit in Excel” feature to open your table in Excel. You should get your prefix_foreignkey_old column with the old foreign keys displayed, as well as the reference to your related table, e.g. prefix_referencetable.prefix_id_old, which is still empty.
Now just copy the complete prefix_foreignkey_old column values into the prefix_referencetable.prefix_id_old column.
Import the changes and you’re done.
Hope this is helpful for some of you out there.

MySQL MERGE Implementation

There are two tables in my MySQL database which have a many-to-many relationship. There is a third table which handles it, with the foreign keys of the first two.
I need to update the relationship. I may have to add a row with a new relation and delete a row that represents a relation that does not exist any more. To take track of the changes, I created a new table that contains all the relations that are valid, and does not contain the old ones that are meant to be deleted.
There is a lot of content on this MERGE statement for SQL, which would solve my problem:
https://www.sqlshack.com/sql-server-merge-statement-overview-and-examples/
https://codingsight.com/merge-updating-source-and-target-tables-located-on-separate-servers/
https://www.sqlservertutorial.net/sql-server-basics/sql-server-merge/
https://www.educba.com/mysql-merge/
The problem is that for some unclear reason MERGE does not exist in MySQL. It kinda has an alternative, called INSERT ... ON DUPLICATE KEY UPDATE, but it is not the same and does not cover what I am aiming here. I don't want to delete all the relations on the table and re-insert the new ones.
I would like to know if there is any other alternative to MERGEin MySQL, or any way to "add" it to my database.

Insert record with foreign key constraints

First of all, my apologies if this question is a duplicate - but I find it difficult, putting short, precise words on my problem.
I've got these entities.
The left contains several groups (like in Unix, in order to make data available to a whole group at once) and at the moment, it's always 1. The right one contains projects - and the middle one makes sure, that one group can gain access to several projects.
As you can see, there are foreign key relationships among them. Now, I want to create a new project in nmd__tree. When doing that, it returns an error:
Cannot add or update a child row: a foreign key constraint fails
(nmd.nmd__tree, CONSTRAINT FK_nmd__tree FOREIGN KEY (treeid)
REFERENCES nmd__helperusergrouphierarchy (treeidfk))
This makes sense, since the nmd_tree relies on a valid foreign key in the helper entity - but at the same time, it presents the problem, that the treeidfk isn't yet known, since it is autogenerated in nmd__tree
A solution could be to remove the relations, insert the record in nmd__tree, extract the newly written primary key (treeid) and create a record in the middle helper entity with the new id. It will work, but is really not very elegant. Also, removed relations presents other, potential problems.
My intentions are to create a query, that deals with this problem by creating both records at once. I know, it isn't possible to make a double insert and found this suggestion (my version doesn't write any records), as well as an article, suggesting stored procedures, which I don't see should make a difference
I would really appreciate a push in the right direction, please.
It seems you've got your constraints defined in the wrong direction; The middle table should have two foreign key constraints not the two end tables. That way, you can insert records in the two end tables and then link them up using the middle table.

Refactoring a One-to-many relation to a Many-to-Many in MySQL: How to formulate the query?

In the initial 'version' of the application that I'm working on, a design consideration wasn't taken into account - no one thought of it.
However, it seems that the original one-to-many relation needs to be refactored into a many-to-many. My question is how best to do this? I'm using MySQL for persistence.
Populating the relationship table will only be a one time effort, I'd rather go with a simple query or a stored procedure approach (I'm not well versed with the latter); rather than write java/jdbc based logic to do it (I know I can and it's not too difficult, but that's not what I want)
So here's an example of the relation:
|VirtualWhiteBoard| -1------*- |Post|
A virtual white board can have many posts. The new functionality is: 1 post should belong to multiple white boards if the user chooses to 'duplicate' current white board (not thought of before)
The schema looks like this:
VirtualWhiteBoard (wallName, projectName,dateOfCreation,..., Primary_Key(wallName, projectName));
Post(post_id, wallName,postData,..., Primary_Key(post_id), Foreign_Key(wallName, projectName));
The virtual white board has a composite primary key (wallName, projectName) and each post has a post_id as primary key
Question: Take the primary keys from VirtualWhiteBoard and Post and add it to the new relation 'has_posts':
|VirtualWhiteBoard| -1------*- |has_Post| -*------1- |Post|
To keep the previous relationships intact and then drop the foreign key column of wallName in Post.
How best to achieve this? Would a query suffice or stored procedures would be required?
(Although I can do this in the 'application' I'd prefer to do it this way, since such refactorings are bound to arise and I don't want unnecessary java-code lying around that'll need to be maintained and would personally prefer to have such a skill too :)
Create your has_Post table with two columns post_id and wallName and populate it with this query:
INSERT INTO has_Post(post_id, wallName) SELECT post_id, wallName FROM Post
Then delete the wallName column from Post table.

MySQL Inserting data and setting FK's?

I have a table like this in my database
http://i.stack.imgur.com/BsoS9.png
I have all my PK,FK relationships setup and im ready to start inserting data.
However I do not know where to start.
Do I insert into tables where my Primary Keys are first.
But then how do I give my Foreign keys the values of the primary key in the linking tables?
I thought with starting with:
-Patient
-Department
-Procedure
-Staff
-Events
-Supplies
Any reference material would be appreciated, I tried googling my question but not luck. Perhaps someone could eloquote it more accurately.
You thought correctly, start with the foremost "parent" table, and work your way down. Inserting the foreign keys can be done either with nested queries or simply getting the key, storing it, and reusing it.
Personally I'd go with nested queries.
Yes, you'll need to logically populate the parent records first. Obviously, you cannot insert a child record without having a parent existing first -- so long as you have true relationships between the two. In your case, just as your diagram suggests, you'll need to populate Events before you can populate Supplies. And then, what ever other logical ties you have.