Entity Framework worked weird when get parent information - linq-to-sql

Currently, I create a table like this:
CREATE TABLE [dbo].[AM_Module](
[ModuleID] [int] IDENTITY(1,1) NOT NULL,
[ModuleName] [nvarchar](100) NULL,
[ParentID] [int] NULL,
CONSTRAINT [PK_AM_ModuleID] PRIMARY KEY CLUSTERED
(
[ModuleID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[AM_Module] WITH CHECK ADD CONSTRAINT [FK_AM_Module_AM_Module_ParentID] FOREIGN KEY([ParentID])
REFERENCES [dbo].[AM_Module] ([ModuleID])
GO
ALTER TABLE [dbo].[AM_Module] CHECK CONSTRAINT [FK_AM_Module_AM_Module_ParentID]
GO
With ParentID contains ModuleID's parent.
And I have 2 row like this:
ModuleID ModuleName ParentID
1 ParentName NULL
2 ChildName 1
Now, in my EF, I run the LinQ to SQL:
var q2 = from a in unitOfWork.RepositoryAsync<AM_Module>().Queryable() where a.ParentID == 1 select a;
var w2 = q2.ToList();
When I check by the SQL Profiler, I see the query will be parsed like this:
SELECT
[Extent1].[ModuleID] AS [ModuleID],
[Extent1].[ModuleName] AS [ModuleName],
[Extent1].[ParentID] AS [ParentID],
FROM [dbo].[AM_Module] AS [Extent1]
WHERE 1 = [Extent1].[ParentID]
The SQL returns 1 row.
But when I check w2[0].AM_Module1 (relationship with itself), I have value of parent with ModuleName too.
Why it happens? The SQL was returned only one row. How the EF know parent's data?
Please advise.

Related

Error on SQL Server tables while performing a join

I'm trying to perform a join between 4 tables schedule table, employee table, machine table and plate table.
Problem is, at schedule table its primary key is a date while on the rest of the table have their primary key as char. I'm trying to convert the primary key in table into char to make it the same as the one on the others but I don't know how. Here is what I have done so far
create table Machine
(
MachineID char(5),
MachineType varchar(10) NOT NULL,
MachineStatus varchar(10)NOT NULL
)
create table Employee
(
EmployeeID char(5) Primary Key,
EmployeeName varchar(30) NOT NULL,
)
create table Plate
(
PlateID char(5) Primary Key,
PlateModel varchar(30) NOT NULL,
)
create table MachineSchedule
(
DateSchedule date Primary Key,
)
here is my join
SELECT Employee.EmployeName, Plate.PlateModel, Machine.MachineID, Machine.MachineType, Machine.MachineStatus
FROM Employee, Plate, Machine
JOIN MachineSchedule
ON MachineSchedule.DateSchedule=Machine.MachineID;
and here is the error it gave Conversion failed when converting date and/or time from character string.
Your Table structure is incorrect, you should use integer datatype for primary key not char or datetime as its creates indexing and we can not join table on char and date datatype they never have same value; and lastly where is the join for other tables in from clause. there should be join condition for Employee, Plate, Machine.
and primary and foreign key constraints also missing
The table design and it's relation are not done properly. Based on this design and relation the simplest solution,i mean the query to make error free:
DROP TABLE [MachineSchedule];
Create The table
CREATE TABLE [dbo].[MachineSchedule](
[DateSchedule] [date] NOT NULL,
[MachineID] [char](5) NULL,
PRIMARY KEY CLUSTERED
(
[DateSchedule] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
Changed Query
SELECT Employee.EmployeeName, Plate.PlateModel, Machine.MachineID, Machine.MachineType, Machine.MachineStatus
FROM Employee, Plate, Machine
JOIN MachineSchedule
ON MachineSchedule.MachineID = Machine.MachineID;
You think
Date column=char column ?
Use with conver to char
For example
On
cast(m.id as char(20))=ma.id
Or update column type

data flow from multiple source to single destinantion in SSIS

I need to import the data from the multiple distributed database ( around 70 ) to the single source table .So how is it possible through SSIS 2008
Assuming that you can run the same query against each of the 70 source servers, you can use a ForEach Loop with a single Data Flow Task. The source connection manager's ConnectionString should be an expression using the loop variables.
Here's an example reading the INFORMATION_SCHEMA.COLUMNS view from multiple DBs. I created the following tables on my local instance:
<!-- language: lang-sql -->
CREATE TABLE [MultiDbDemo].[SourceConnections](
[DatabaseKey] [int] IDENTITY(1,1) NOT NULL,
[ServerName] [varchar](50) NOT NULL,
[DatabaseName] [varchar](50) NOT NULL,
CONSTRAINT [PK_SourceConnections] PRIMARY KEY CLUSTERED
(
[DatabaseKey] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
CREATE TABLE [MultiDbDemo].[SourceColumns](
[ColumnKey] [int] IDENTITY(1,1) NOT NULL,
[ServerName] [varchar](50) NOT NULL,
[DatabaseName] [varchar](50) NOT NULL,
[SchemaName] [varchar](50) NOT NULL,
[TableName] [varchar](50) NOT NULL,
[ColumnName] [varchar](50) NOT NULL,
CONSTRAINT [PK_SourceColumns] PRIMARY KEY CLUSTERED
(
[ColumnKey] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
This is the control flow for the SSIS package:
The Source_AdoDotNet connection manager's ConnectionString property is set to the following expression:
SQL_GetSourceList's SQLStatement property is SELECT ServerName, DatabaseName FROM MultiDbDemo.SourceConnections, and the ResultSet is mapped to the User::SourceList variable.
The ForEach Loop task is configured thusly:
Note that the ADO object source variable is set to the User::SourceList variable populated in the SQL_GetSourceList task.
And the data flow looks like this:
ADO_SRC_SourceInfo is configured thusly:
The next effect of all this is that, for each database listed in the SourceConnections table, we execute the query SELECT LEFT(TABLE_SCHEMA, 50) AS SchemaName, LEFT(TABLE_NAME, 50) AS TableName, LEFT(COLUMN_NAME, 50) AS ColumnName FROM INFORMATION_SCHEMA.COLUMNS and save the results in the SourceColumns table.
You will still need 70 destination components. Simply specify the same table in all of them.

Issue with linq2sql with this specific stituation

Software used:
Visual studio 2008 professional with services pack 1
Sql Server 2005 Standard Edition (9.00.4266.00)
Windows XP SP3
I have these 3 tables:
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Table_2](
[table2id] [int] IDENTITY(1,1) NOT NULL,
[table2filler] [varchar](max) NULL,
CONSTRAINT [PK_Table_2] PRIMARY KEY CLUSTERED
(
[table2id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Table_1](
[table1id] [int] IDENTITY(1,1) NOT NULL,
[table1guid] [uniqueidentifier] NOT NULL,
CONSTRAINT [PK_Table_1] PRIMARY KEY CLUSTERED
(
[table1id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
CREATE UNIQUE NONCLUSTERED INDEX [IX_Table_1] ON [dbo].[Table_1]
(
[table1guid] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Table_3](
[tableguid] [uniqueidentifier] NOT NULL,
[table2id] [int] NOT NULL,
[table3filler] [varchar](max) NULL,
CONSTRAINT [PK_Table_3] PRIMARY KEY CLUSTERED
(
[tableguid] ASC,
[table2id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
ALTER TABLE [dbo].[Table_3] WITH CHECK ADD CONSTRAINT [FK_Table_3_Table_1] FOREIGN KEY([tableguid])
REFERENCES [dbo].[Table_1] ([table1guid])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[Table_3] CHECK CONSTRAINT [FK_Table_3_Table_1]
GO
ALTER TABLE [dbo].[Table_3] WITH CHECK ADD CONSTRAINT [FK_Table_3_Table_2] FOREIGN KEY([table2id])
REFERENCES [dbo].[Table_2] ([table2id])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[Table_3] CHECK CONSTRAINT [FK_Table_3_Table_2]
GO
INSERT INTO [dbo].[Table_2]
([table2filler])
VALUES
('test')
print 'table2id:'
print scope_identity()
GO
declare #guid uniqueidentifier
set #guid=newid()
print 'table1guid:'
print #guid
INSERT INTO [dbo].[Table_1]
([table1guid])
VALUES
(#guid)
GO
now open a new web apps project, create a new dbml and drag&drop these 3 tables
now just put that code in a webpage codebehind
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim test As New Table_3
Dim db As New DataClasses1DataContext
test.table2id = 1
test.tableguid = New Guid("guid from table 1")
test.table3filler = "a"
db.Table_3s.InsertOnSubmit(test)
db.SubmitChanges()
End Sub
and run it
you will get an invalid cast error
only way so far for me to be able to run that code is to remove the link between the table inside the DBML
is there a way to do that insert without removing the link between the tables?
I actually created your database just as you specified and ran exactly this code it locally on my box. I get no such error when I substitute the a real GUID in this line:
test.tableguid = New Guid("guid from table 1")
Are you sure your GUIDs are in the right format? Are you sure your tables are created exactly like you specified? Double check it... My guess is that if you recreate this sample db from scratch, you won't see this problem.
I believe Linq2sql doesn't like it when you set a foreign key id directly. It prefers you to set the foreign object itself.
test.table_2 = db.Table_2.First(t2 => t2.table2id = 1);
test.tableguid = New Guid("guid from table 1")
test.table3filler = "a"
ok, it's in fact a bug with .net 3.5 and fixed with .net 4.0
but there is a hotfix, see detail here
everything work like it should after that hotfix is installed

Instead Of Delete Trigger with FileStream

Why can't i use an Instead Of Delete Trigger on a table that has a varbinary filestream column?
Is there a workaround for it?
I want to update a field when a delete command is performed.
Thanks
You may create two tables istead of one:
CREATE TABLE [dbo].[FileStreams](
[Id] [int] IDENTITY(1,1) NOT NULL,
[RowGuid] [uniqueidentifier] ROWGUIDCOL NOT NULL,
[Data] [varbinary](max) FILESTREAM NULL,
CONSTRAINT [PK_FileStreams] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
UNIQUE NONCLUSTERED
(
[RowGuid] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] FILESTREAM_ON [FilestreamGroup]
GO
CREATE TABLE [dbo].[Files](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](1024) NULL,
[FileStreamId] [int] NOT NULL,
CONSTRAINT [PK_Files] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[Files] WITH CHECK ADD CONSTRAINT [FK_Files_FileStreams] FOREIGN KEY([FileStreamId])
REFERENCES [dbo].[FileStreams] ([Id])
GO
ALTER TABLE [dbo].[Files] CHECK CONSTRAINT [FK_Files_FileStreams]
GO
Foreign key must be NO ACTION. It allows you to create INSTEAD OF trigger for table Files
All types of INSTEAD OF triggers are generally not supported with filestream tables - and DELETE is no different in this case. The reason is probably that it would have very complicated semantics in case of UPDATE triggers and out-of-band updates (from .Net or Win32).
If you provide some more details regarding your scenario then perhaps someone will be able to give you a workaround.

What is a reason that LINQ to SQL wouldn't generate a collection based on a relationship?

I have a relationship between two entities (e1 and e2) and e1 has a collection of e2, however I have a similar relationship set up between (e2 and e3), yet e2 does not contain a collection of e3's, any reason why this would happen? Anything I can post to make this easier to figure out?
Edit: I just noticed that the relationship between e1 and e2 is solid and between e2 and e3 is dotted, what causes that? Is it related?
Using this setup, everything worked.
1) LINQ to SQL Query, 2) DB Tables, 3) LINQ to SQL Data Model in VS.NET 2008
1 - LINQ to SQL Query
DataClasses1DataContext db = new DataClasses1DataContext();
var results = from threes in db.tableThrees
join twos in db.tableTwos on threes.fk_tableTwo equals twos.id
join ones in db.tableOnes on twos.fk_tableOne equals ones.id
select new { ones, twos, threes };
2 - Database Scripts
--Table One
CREATE TABLE tableOne(
[id] [int] IDENTITY(1,1) NOT NULL,
[value] [nvarchar](50) NULL,
CONSTRAINT [PK_tableOne] PRIMARY KEY CLUSTERED
( [id] ASC ) WITH (
PAD_INDEX = OFF,
STATISTICS_NORECOMPUTE = OFF,
IGNORE_DUP_KEY = OFF,
ALLOW_ROW_LOCKS = ON,
ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY];
--Table Two
CREATE TABLE tableTwo(
[id] [int] IDENTITY(1,1) NOT NULL,
[value] [nvarchar](50) NULL,
[fk_tableOne] [int] NOT NULL,
CONSTRAINT [PK_tableTwo] PRIMARY KEY CLUSTERED
( [id] ASC ) WITH (
PAD_INDEX = OFF,
STATISTICS_NORECOMPUTE = OFF,
IGNORE_DUP_KEY = OFF,
ALLOW_ROW_LOCKS = ON,
ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY];
ALTER TABLE tableTwo WITH CHECK
ADD CONSTRAINT [FK_tableTwo_tableOne]
FOREIGN KEY([fk_tableOne])
REFERENCES tableOne ([id]);
ALTER TABLE tableTwo CHECK CONSTRAINT [FK_tableTwo_tableOne];
--Table Three
CREATE TABLE tableThree(
[id] [int] IDENTITY(1,1) NOT NULL,
[value] [nvarchar](50) NULL,
[fk_tableTwo] [int] NOT NULL,
CONSTRAINT [PK_tableThree] PRIMARY KEY CLUSTERED
([id] ASC ) WITH (
PAD_INDEX = OFF,
STATISTICS_NORECOMPUTE = OFF,
IGNORE_DUP_KEY = OFF,
ALLOW_ROW_LOCKS = ON,
ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY];
ALTER TABLE tableThree WITH CHECK
ADD CONSTRAINT [FK_tableThree_tableTwo]
FOREIGN KEY([fk_tableTwo])
REFERENCES tableTwo ([id]);
ALTER TABLE tableThree CHECK CONSTRAINT [FK_tableThree_tableTwo];
3 - LINQ to SQL Data Model in Visual Studio
alt text http://i478.photobucket.com/albums/rr148/KyleLanser/ThreeLevelHierarchy.png
the FK_Contraints are set up like this:
ALTER TABLE [dbo].[e2] WITH CHECK ADD CONSTRAINT [FK_e2_e1] FOREIGN KEY([E1Id]) REFERENCES [dbo].[e1] ([Id])
ALTER TABLE [dbo].[e3] WITH CHECK ADD CONSTRAINT [FK_e3_e2] FOREIGN KEY([E2Id]) REFERENCES [dbo].[e2] ([Id])
is this what you were asking for?