Defining View in Entity Data Model - sql-server

I am trying to add a view to an entity data model but I get the error below.
The view is a group by with a count. I don’t understand this because a view does not have a primary key by it’s nature.
I modified the original post because I figured out how to add a key to the view. But I still have the same problem.
warning 6013: The table/view
'fmcsa.dbo.vieFMCSADocumentCount' 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.
Here is the View
CREATE VIEW [dbo].[vieFMCSADocumentCount] with SCHEMABINDING
AS
SELECT COUNT_BIG(*) AS CountOfDocs, ROLE_ID, OWNER_ID
FROM dbo.FMCSA_DOCUMENT
GROUP BY ROLE_ID, OWNER_ID
then I can add a key
CREATE UNIQUE CLUSTERED INDEX [MainIndex] ON [dbo].[vieFMCSADocumentCount]
(
[OWNER_ID] ASC,
[ROLE_ID] ASC
)
Still not working.

You didn't specify, but I'm assuming you're using EF4. I've come across this before--you either want to define a key manually or edit recreate your view WITH SCHEMABINDING and reimport.
Schema binding effectively tells SQL to track dependencies for your view. It's both a blessing and a curse (try adding a column to FMCSA_DOCUMENT once this view has schema binding), so you might want to read up on the effects.
CREATE VIEW [dbo].[vieFMCSADocumentCount] WITH SCHEMABINDING
AS
SELECT COUNT(ID) AS CountOfDocs, ROLE_ID, OWNER_ID
FROM dbo.FMCSA_DOCUMENT GROUP BY ROLE_ID, OWNER_ID
Alternately, in the EF Model Browser Go to the Entity Types folder, find your view (right click and choose Show in Designer). Then on the view, highlight the column(s) that comprise your primary key and right click and choose "Entity Key"

Related

SQLSERVER - how to define a procedure for table id generation?

I'm application switching databases for my application from MySQL to SQLServer.
Today I implement a custom id generation strategy defined in an abstract class all POJOs use. This works, but I am only able to generate an id via the application.
With this database migration, I'd like, after creating the schema, define somewhere all the 'id' columns for all tables to use a procedure that returns a SELECT NEWID(); query.
Is this possible? How?
I like to define the ID columns with a default constraint:
create table a
(
id
uniqueidentifier not null
constraint [a.id.default.newid]
default( newid() )
constraint [a.id.primarykey]
primary key clustered,
--> other columns...
)
This way, you can either take an app-generated ID or let the database assign it, depending on your needs. Your primary key constraint (or unique constraint) enforces uniqueness...which is important if you allow incoming IDs from the apps.
In the scripts...where you don't necessarily have the need to generate the ID, don't specify a value...and the default kicks in. You can insert newid(), too...
insert a
select newid()
from b
...and SQL Server knows to call newid() for each row

How do I get MS LightSwitch to recognize my View?

I've created a View from a table in another database. I have dbo rights to the databases so viewing and updating is not a problem. This particular View did not have an "id" column. So I added one to the View by using ROW_NUMBER. Now I had a problem with a table, in the same database, not showing up in LightSwitch but that was solved by changing the id column to be NOT NULL. I haven't done any real manipulation in LightSwitch. I'm still in the Import Your Data Source stage (ie. very beginning).
This View, in LightSwitch, is going to be read-only. No updating or deleting. From what I've read, LightSwitch needs a way to determine the PK of a Table or View. It either reads it from the schema (column set as a PK) or finds a column set as NOT NULL and uses that as the PK. Well I can't seem to do either of those things in SQL Server or LightSwitch, so I am stuck as to how to get LightSwitch to "see" my View.
for lightswitch to see your view you must have a primary key on a column of the table your are selecting from.
Example:
create table tbl_test
(
id int identity primary key not null,
value varchar(50)
)
create view vw_test
as
select *
from tbl_test
note:sometimes when you edit the primary key column in the view select statement it may cause lightswitch to not see it
Example:
create view vw_test
select cast(id as varchar(50) id,...
lightswitch would not see the table
Hope this was helpful! :)
What I do in this case is create a view with an ID column equal to the row number. Ensure the column you're basing the ID on is not null using the isnull() or coalesce() functions.
Example:
create view as
select distinct ID = row_number() over (order by isnull(Name,'')),
Name = isnull(Name,'')
from My_Table

Updating foreign keys in SQLServer like Access

I have a table, Contacts, with a primary key of ContactID, which is an identity column. I have another table, Person, with a primary key of PersonID that is a foreign key to ContactID. When I insert a record into Person, I would like PersonID to pull the corresponding identity from ContactID in Contact.
In Access, I simply make a query that references both tables, and it will fill in the foreign key column with the corresponding value in the identity (autonumber) column.
SELECT Person.PersonID, Person.FirstName, Person.MiddleName, Person.LastName, Contact.ContactID, Contact.EmailAddress, Contact.PhoneNumber
FROM (Contact INNER JOIN Person ON Contact.ContactID = Person.PersonID);
How can we achieve this in SQLServer 2008 R2? I have been programming triggers to update the keys, but it seems like there ought to be a better way.
Thank you very much for your assistance.
When you insert to the first table, you use the OUTPUT clause to pull the identity value and then you can use it to insert to the child table.
You can also use scope_identity() to do the same thing, but OUTPUT is the preferred method. Do not under any circumstances use ##Identity as it often will give incorrect results and mess up your data integrity.
Look up how to use them in Books Online.

Defining a one-to-one relationship in SQL Server

I need to define a one-to-one relationship, and can't seem to find the proper way of doing it in SQL Server.
Why a one-to-one relationship you ask?
I am using WCF as a DAL (Linq) and I have a table containing a BLOB column. The BLOB hardly ever changes and it would be a waste of bandwidth to transfer it across every time a query is made.
I had a look at this solution, and though it seems like a great idea, I can just see Linq having a little hissy fit when trying to implement this approach.
Any ideas?
One-to-one is actually frequently used in super-type/subtype relationship. In the child table, the primary key also serves as the foreign key to the parent table. Here is an example:
CREATE TABLE Organization
(
ID int PRIMARY KEY,
Name varchar(200),
Address varchar(200),
Phone varchar(12)
)
GO
CREATE TABLE Customer
(
ID int PRIMARY KEY,
AccountManager varchar(100)
)
GO
ALTER TABLE Customer
ADD FOREIGN KEY (ID) REFERENCES Organization(ID)
ON DELETE CASCADE
ON UPDATE CASCADE
GO
Why not make the foreign key of each table unique?
there is no such thing as an explicit one-to-one relationship.
But, by the fact that tbl1.id and tbl2.id are primary keys and tbl2.id is a foreign key referenceing tbl1.id, you have created an implicit 1:0..1 relationship.
Put 1:1 related items into the same row in the same table. That's where "relation" in "relational database" comes from - related things go into the same row.
If you want to reduce size of data traveling over the wire consider either projecting only the needed columns:
SELECT c1, c2, c3 FROM t1
or create a view that only projects relevant columns and use that view when needed:
CREATE VIEW V1 AS SELECT c1, c2, c3 FROM t1
SELECT * FROM t1
UPDATE v1 SET c1=5 WHERE c2=7
Note that BLOBs are stored off-row in SQL Server so you are not saving much disk IO by vertically-partitioning your data. If these were non-BLOB columns you may benefit form vertical partitioning as you described because you will do less disk IO to scan the base table.
How about this. Link the primary key in the first table to the primary key in the second table.
Tab1.ID (PK) <-> Tab2.ID (PK)
My problem was I have a 2 stage process with mandatory fields in both. The whole process could be classed as one episode (put in the same table) but there is an initial stage and final stage.
In my opinion, a better solution for not reading the BLOB with the LINQ query would be to create a view on the table that contains all the column except for the BLOB ones.
You can then create an EF entity based on the view.

Defining Multiple Foreign Keys in Visual Studio

I have a basic database schema as follows (dumbed down so it's easy to read):
[Staff]
StaffId (pk)
FirstName
LastName
[RosterEvent]
EventId (pk)
StartDate
EndDate
[StaffEvents]
StaffId (pk)
EventId (pk)
Ok so, many Staff can have many RosterEvents, which is why I added the StaffEvents table. It resolves the many-to-many relationship. However I do not know how to define the foreign keys.
In Visual Studio, how do I define these as foreign keys using the Table Designer? If I try to add the relationship using the Foreign Key Relationships dialog box, I get the error message "The columns in table 'StaffEvents' do not match an existing primary key or UNIQUE constraint". Even though the UNIQUE constraint has been applied to all primary keys on every table.
Help is much appreciated! Thanks!
In the table designer you can click the row headers on the side of the two columns you want and click the primary key icon on the toolbar.
Are your PK actually marked as Primary Keys or just UNIQUE? Are they the same data-type?
All primary keys on every table are marked as PK and UNIQUE. They are also all of type int.
This is how I am trying to set up the relationship at the moment.
From the Staff table I click the 'Relationships' toolbar button.
I click 'Add'
I click on the (...) from the 'Tables and Columns Specifications' property.
I select 'StaffEvents' as the primary key table.
I select 'StaffId' from the drop down box.
When I click OK, I get the error message "The columns in table 'StaffEvents' do not match an existing primary key or UNIQUE constraint".

Resources