Is it possible to set constraints in DataContext generated from LINQ ORM? - sql

I am working on a database whose tables won't have any foreign key constraints except composite primary keys for some of the tables. Is it possible to map the database using LINQ to SQL and then set the foreign key constraints in the DataContext being generated?
Thanks

Yes it is possible.
If they don't exist you just have to create them manually in the designer - use the Inheritance tool from the designer view and drag from the primary key on one table to the foreign key on the other.
Important notes:
1) both tables must have a primary key defined: see my blog entry on this point
2) the datatypes of the two columns must match - an integer cannot join to a date

Related

SQL What is the Purpose of 1 to 1 self reference on primary key? [duplicate]

I went over a legacy database and found a couple of foreign keys that reference a column to itself. The referenced column is the primary key column.
ALTER TABLE [SchemaName].[TableName] WITH CHECK ADD
CONSTRAINT [FK_TableName_TableName] FOREIGN KEY([Id])
REFERENCES [SchemaName].[TableName] ([Id])
What is the meaning of it?
ALTER TABLE [SchemaName].[TableName] WITH CHECK ADD
CONSTRAINT [FK_TableName_TableName] FOREIGN KEY([Id])
REFERENCES [SchemaName].[TableName] ([Id])
This foreign key is completely redundant and pointless just delete it. It can never be violated as a row matches itself validating the constraint.
In a hierarchical table the relationship would be between two different columns (e.g. Id and ParentId)
As for why it may have been created quite likely through use of the visual designer if you right click the "Keys" node in object explorer and choose "New Foreign Key" then close the dialogue box without deleting the created foreign key and then make some other changes in the opened table designer and save it will create this sort of redundant constraint.
In some cases this is a preferred way to reduce redundancy in your model. In using the self referencing foreign key (as shown in you example) you create a hierarchical relationship between rows in your table. Pay attention to what happens when you delete a row from the table, cascading on delete might remove rows you still want.
Using these sort of keys moves some of the data validation to the DB model as opposed to making this a responsibility of the program/programmer. Some outfits prefer this way of doing things. I prefer to make sure programs and programmers are responsible - data models can be hard to refactor and upgrade in production environments.

Last Modified By fields and foreign keys

In SQL Server 2012, I have a User table to store application users. I also have an Organization table which has a LastModifiedBy field in which I would like to store the UserID of the last person to modify the values within the table via an ASPX page. Should I create a foreign key relationship between the LastModifiedBy field and the UserID field within the Users table?
I would also like to add a LastModifiedBy field to the Users table itself. Should/can I create a self referencing foreign key constraint on this table? If this is possible, is it a horrible idea?
Any perspectives on pros and cons of creating these foreign key constraints would be greatly appreciated.
What you are describing is what foreign keys are made for. These foreign keys are at the very core of relational databases. Even if they might give a slight performance impact when inserting new rows, because it has to check if the referenced key exists, it should not be avoided.

Set on demand foreign key in DataBase

I have table in my data base with these specs:
one PK
3 fields with foreign key
some statistic fields
problem is here:
In every row only one FK field will be filled.
What is the best solution A or B?
A- define 3 FK for my table
B- define one field as FK_TYPE and one field as DEMAND_FK and use checking on FK_TYPE for result
Option A - if you've got to have this design, you'll need a separate column for each foreign key. There's no (standard) way to define a "conditional" foreign key.
If your system supports check constraints, include a check constraint so that exactly one of the FK columns is not null. If it doesn't support check constraints, add triggers that enforce this same check.
If I am not wrong, B can not be possible in any relational database. Foreign key can only reference to only one primary key of a table. If you use B then you have to add the constrain in application level. Otherwise use A.

How can I replace the existing primary key with a new primary key on my table?

I'm working with a legacy SQL Server database which has a core table with a bad primary key.
The key is of type NVARCHAR(50) and contains an application-generated string based on various things in the table. For obvious reasons, I'd like to replace this key with an auto-incrementing (identity) INT column.
This is a huge database and we're upgrading it piece-by-piece. We want to minimize the changes to tables that other components write to. I figured I could change the table without breaking anything by just:
Adding the new Id column to the table and making it nullable
Filling it with unique integers and making it NOT NULL
Dropping the existing primary key while ensuring there's a uniqueness constraint still on that column
Setting the new Id column to be the new primary key and identity
Item 3 is proving very painful. Because this is a core table, there are a lot of other tables with foreign key constraints on it. To drop the existing primary key, it seems I have to delete all these foreign key constraints and create them again afterwards.
Is there an easier way to do this or will I just have to script everything?
Afraid that is the bad news. We just got through a big project of doing the same type of thing, although our head DBA had a few tricks up his sleeve. You might look at something like this to get your scripts generated for the flipping of the switch:
I once did the same thing and basically used the process you describe. Except of course you have to first visit each other table and add new foreign key pointing to the new column in your base table
So the approach I used was
Add a new column with an auto incrementing integer in the base table, ensure it has a unique index on it (to be replaced later by the primary key)
For each foreign key relationship pointing to the base table add a new column in the child table. (note this can result in adding more than one column in the child table if more than one relationship)
For each instance of a key in the child table enter a value into the new foreign key field(s)
Replace your foreign key relationships such that the new column now serves
Make the new column in the base table the primary
Drop the old primary key in the base table and each old foreign key in the
children.
It is doable and not as hard as it might sound at first. The crux is a series of update statements for the children table of the nature
Update child_table
set new_column = (select new_primary from base)
where old_primary = old_foreign

Microsoft Access - SQL - Internal Foreign Key

Does MS Access 2007 support internal foreign keys within the same table?
Yes. Create the table with the hierarchy.
id - autonumber - primary key
parent_id - number
value
Go to the relationships screen. Add the hierarchy table twice. Connect the id and the parent_id fields. Enforce referential integrity.
Yes it does.
Under database tools and relationships you need to show 2 copies of the self-referencing table. It will name the second copy Table_1. Then you setup a relationship between the primary key in "table" and the foreign key column(s) in "Table_1".
Yes it does and unlike many more capable SQLs (e.g. SQL Server) you can also use CASCADE referential actions on FKs within the same table, which is nice.