Sql Server CE foreign key shows up as primary key - visual-studio

At least, that's how it looks to me. I'm using Sql Server CE 4.0 and Visual Studio 2010. This is the first time I've used Sql Server CE.
For example, I have two tables. One is called Templates:
TemplateID (int, primary key, identity)
TemplateName (nvarchar)
The other is called Products:
ProductID (int, primary key, identity)
TemplateID (int, foreign key relationship with Templates)
ProductName (nvarchar)
After creating these tables, I attempted to set up a foreign key relationship between the tables on the TemplateID field in Products and the TemplateID field in Templates.
After setting up the relationship, when I look at the Products table in the Server Explorer, I see that TemplateID has been flagged as a primary key in Products. This is NOT supposed to be a primary key in that table!
Is this simply some oddity of presentation for CE tables -- meaning the foreign key is a primary key in some other table? It doesn't seem so, because clicking on the TemplateID column in the Products table, and expanding the Identity tag in the Properties window, shows that the "Table" is Products, not Templates.
If anyone could shed light on this strangeness I would really appreciate it.

Some testing confirmed that the foreign keys are NOT included as part of the primary key, the display in Visual Studio notwithstanding.
So, apparently it's just a clumsy, confusing way of displaying the fields of the tables in Visual Studio Server Explorer.
Yeesh. I miss Management Studio already ...

Related

Oracle SQL Developer - using foreign keys

First of, this is a pretty basic question but I cant seem to find a basic tutorial on how to use the software.
If i have a table named COUNTRY with the field region_id
and then another table named REGION with a primary key as region_id.
I want to set the region_id field in COUNTRY table as a foreign key.
Are the following steps correct?
Go to constraints, add a new foreign key.
Select COUNTRY as table
Change local column to region_id
![enter image description here][1]
Am I doing it correctly? if not, where am i going wrong
Yes, This is the correct procedure.
If you want your foreign key to have additional behavior (e.g., ON DELETE CASCADE), you can use the "on delete" drop-down in the wizard.
I cant seem to find a basic tutorial on how to use the software.
Have you looked at the Oracle Learning Library for SQL Developer tutorials?
If you search for: Getting Started with Oracle SQL Developer 4.0 you will find a tutorial that gets you up and running SQL Developer, this tutorial includes how to create Foreign Key Constraints.

Webmatrix starter site userprofile fkey with othet table

I want to add to the UserProfile table of the StarterSite database created by the WebMatrix Starter Site template another column named email_pk (varchar 50) as primary key and add to id a foreign key constraint that references the Email column (varchar 50) of a new tb_contacts table. The latter column isn't a primary key.
When I try to do that manually in the WebMatrix Database workspace I get the following error:
There are no primary or candidate keys in the referenced table 'dbo.UserProfile' that match the referencing column list in the foreign key 'FK_tb_admin_user_UserProfile'.
Could not create constraint. See previous errors.
System.Data.SqlClient.SqlException (0x80131904): There are no primary or candidate keys in the referenced table 'dbo.UserProfile' that match the referencing column list in the foreign key 'FK_tb_admin_user_UserProfile'.
Could not create constraint. See previous errors.
at Microsoft.WebMatrix.DatabaseManager.SqlDatabase.SqlDatabaseProvider.EditTable(String connectionString, String schema, TableInfo tableInfo)
at Microsoft.WebMatrix.DatabaseManager.IisDbManagerModuleService.EditTable(DatabaseConnection databaseConnection, String schema, Object tableInfoData, String configPathState)
at Microsoft.WebMatrix.DatabaseManager.Client.ClientConnection.EditTable(String schema, Object tableInfoData)
at Microsoft.WebMatrix.DatabaseManager.Client.ClientTable.CommitChanges()
at Microsoft.WebMatrix.DatabaseManager.Client.TableDesignerViewModel.PerformSave()
ClientConnectionId:1da00f40-8f46-4c5b-b423-905c6990fd0d
If you want to add a foreign key to your UserProfile table, the referenced column must be a primary key or have a unique constraint.
You could manually add a unique constraint with a query like this:
ALTER TABLE tb_contacts
ADD UNIQUE (Email)
By the way, the New Relationship dialog of the WebMatrix Databases workspace displays as possible references only the tables with suitable primary keys.
Note that your StarterSite db alterations inhibit the use of the WebSecurity class.

Is there a table designer for VS2010 database project?

Am I missing something here? It seems that the only options to create a new table in a database project in VS2010 is:
Create a table object as a file, then create all constraints (defaults) as separate files, then create each index as a separate file, and primary key as a separate file and on and on...
Or
Create the entire table schema using the table designer in SSMS and then use the schema compare tool to create a single monolithic file of SQL statements for each element of the table and copy each block of code to a newly created file in VS.
This question was asked 2 years ago and I'm hoping the answer has changed.
Please tell me there's a hidden table designer for the database project in VS2010 that I have just overlooked.
I'm pretty sure there isn't one!
Can I ask why you need a table designer over creating and modifying creation script files for your new objects? Is there anything that this doesn't give you that a designer would?
I just noticed that VS 11 Beta now includes a designer, although it is rough around the edges (relationships, for example, still need to be typed by hand).
The way I use the database project in VS2010 is:
Create everything with SQL Server Management Studio.
Synchronize it into my database project.
When I need to change something, do it in SQL Server Management Studio.
Use Schema Comparisons to synchronize your database project.
Wow... can't believe no one has taken the time to answer this in all this time. Here's a sample of table creation script with some simple constraints.
CREATE TABLE [User]
(
UserID INT NOT NULL IDENTITY (1,1),
UserName NVARCHAR(20) NOT NULL,
UserPassword NVARCHAR(20) NOT NULL,
EmailAddress NVARCHAR(50) NOT NULL,
Location NVARCHAR(100),
MobileNumber VARCHAR(10),
CreatedDate DATETIME NOT NULL
CONSTRAINT User_CreatedDate_DF DEFAULT (GETDATE()),
CONSTRAINT User_UserID_PK PRIMARY KEY CLUSTERED (UserID),
CONSTRAINT User_UserName_UQ UNIQUE (UserName),
CONSTRAINT User_EmailAddress_CK CHECK (EmailAddress LIKE '%#%.%'),
CONSTRAINT User_MobileNumber_CK CHECK (MobileNumber LIKE '[2-9][0-9][0-9][2-9][0-9][0-9][0-9][0-9][0-9][0-9]')
)
You can use functions to embed in your check constraints, but again, this is a simplistic exaxmple.
As I commented here, the VS2010 reference states that there exist a Table Designer in this document.
But for some reason, no matter what kind of project I create (Server project 2008/2005, database project 2008/2005) I can't get the Table Designer being shown.

Linq2Sql: Can I create entities with foreign key relationships without a primary key in both tables?

I have 2 tables in my database that I'm trying to create Linq2Sql entities for. There's more to them than this, but this is essentially what they come down to:
Rooms UserActivity
-------- --------
RoomID ActivityID
RoomID (foreign key on Rooms.RoomID)
The UserActivity table is essentially just a log for actions a user performs against the Rooms table.
Since the UserActivity table is only used for logging actions taken, it didn't make a lot of sense (to me at least) to create a primary key for the table originally, until the Linq2Sql mapper refused to make UserActivity a part of the Room entity in my Linq entities. When I set up the entities in the Visual Studio designer, I got these 2 warnings:
Warning 1 DBML1062: The Type attribute 'UserActivity' of the Association element 'Room_UserActivity' of the Type element 'Room' does not have a primary key. No code will be generated for the association.
Warning 2 DBML1011: The Type element 'UserActivity' contains the Association element 'Room_UserActivity' but does not have a primary key. No code will be generated for the association.
These warnings led me to create the ActivityID column in my table as displayed above.
What I'd like to know is if there is any way to allow Linq2Sql to create relationships between my entities without having a primary key in both tables. If I don't have the primary key in the UserActivity table, the entities can still be created, but the relationships aren't generated.
Is is it possible to do this, or should I try to make sure my tables always have a primary key in them as a general good practice?
Any table that stores real data in your app should always have a primary key - most cases, in SQL Server environments, a INT IDENTITY(1,1) will be just fine. You don't have to keep track of those, no bookkeeping necessary etc. It doesn't cost you much, totally easy to do - I don't see any reason why not have a primary key, even on your UserActivity table.
ALTER TABLE UserActivity
ADD UserActivityID INT IDENTITY(1,1)
CONSTRAINT PK_UserActivity PRIMARY KEY
and you're done!
The only time I would say no primary key is needed is for things like temporary tables when bulk importing huge amounts of data, or other temporary scenarios.
Marc
You need a primary key to create relationships.
It's good practise to always design tables with primary keys, even if you add surrogate (auto increment identity).

Visual Studio Database Pro Partial Projects Constraints Issue

In Visual Studio 2008 Database edition one can use "partial projects" to allow a database to be separated into multiple projects for deployment and maintainability. I have been looking into doing this with our project but hit the following snag:
If you have project that defines some base tables, and then you have a different project that defines a new set of tables that have constraints pointing to the tables in the first project, DBPro seems unable to map this relationship. The specific error is:
"CONSTRAINT has an unresolved reference to Table foo" (where foo is in the original DB).
A more concrete example if you'd like to duplicate for yourself the scenario:
Create a Project called BaseDB.
Define in BaseDB a table called Users with the following DDL:
CREATE TABLE [dbo].[Users] (
UserID INT IDENTITY(1,1) PRIMARY KEY,
UserName NVARCHAR(20) NOT NULL
)
Export BaseDB as a partial project adding the _BaseDB.files file to your project.
Create a Project in the same solution called DerivedDB
Use the Import Partial Project to point to BaseDB, confirming if you like that there's a stub reference in your import files pointing to the Users table in BaseDB.
Define a table in DerivedDB called PowerUsers with the following DDL:
CREATE TABLE [dbo].[PowerUsers] (
PowerUserID INT IDENTITY(1,1) PRIMARY KEY,
UserID INT NOT NULL
)
If you do a "Build" at this point, everything works.
Add a FOREIGN KEY CONSTRAINT in the DerivedDB project from PowerUsers to Users with the following DDL:
ALTER TABLE [dbo].[PowerUsers]
ADD CONSTRAINT [PowerUsers_Users_FK]
FOREIGN KEY (UserID)
REFERENCES [dbo].[Users] (UserID)
Performing the above steps should allow you to see the error I'm talking about.
Questions:
Is there a way to fix constraint references across database projects?
If not, should partial projects then be reserved for series of stored procedures and the base project reserved for all DDL of base tables and constraints?

Resources