EF6.1.3 Join columns (like in hibernate) - entity-framework-6

I'm using Entitiy Framework 6.1.3 and I want to add a relation from N tables to 1 table with more than 1 join columns. The following example will help you to understand my problem:
Table P (protocol table) with these columns:
protocol_id (int, PK)
message (string)
module (string)
reference_id (int)
protocol_id | module | message | reference_id
-----------------------------------
1 | A | created | 1
2 | A | modified | 1
2 | A | created | 2
3 | B | deleted | 1
4 | B | modified | 1
Table A (module A table) with these columns:
mod_id (int, PK)
mod_x (string)
mod_y (...)
...
mod_id | mod_x | ...
--------------------
1 | abc | ...
2 | xyz | ...
Table B (module B table) with these columns:
mod_id (int, PK)
mod_x (string)
mod_y (...)
...
mod_id | mod_x | ...
--------------------
1 | abc | ...
2 | xyz | ...
I would like to have a navigation property in module A to get all procotols for this row - sthg like that:
where module = 'A' and reference_id = mod_id
(same for module B, module C ...)
In Java/Hibernate, I know you can use more than one ElementJoinColumns (with referenceColumnsNames, ...).
How can I handle this with EF6.1?
Thanks, Markus.

Here is the DDL. It is important that you have the proper referential integrity (RI) set up:
USE [Breaz]
GO
/****** Object: Table [dbo].[TableA] Script Date: 9/14/2016 3:25:43 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[TableA](
[mod_id] [int] IDENTITY(1,1) NOT NULL,
[mod_x] [varchar](10) NULL,
CONSTRAINT [PK_TableA_] PRIMARY KEY CLUSTERED
(
[mod_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
SET ANSI_PADDING OFF
GO
/****** Object: Table [dbo].[TableB] Script Date: 9/14/2016 3:25:43 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[TableB](
[mod_id] [int] IDENTITY(1,1) NOT NULL,
[mod_x] [varchar](10) NULL,
CONSTRAINT [PK_tableb] PRIMARY KEY CLUSTERED
(
[mod_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
SET ANSI_PADDING OFF
GO
/****** Object: Table [dbo].[TableP] Script Date: 9/14/2016 3:25:43 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[TableP](
[protocol_id] [int] IDENTITY(1,1) NOT NULL,
[message] [varchar](10) NULL,
[module] [varchar](10) NULL,
[reference_id] [int] NULL,
CONSTRAINT [PK_TableP] PRIMARY KEY CLUSTERED
(
[protocol_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
SET ANSI_PADDING OFF
GO
ALTER TABLE [dbo].[TableP] WITH CHECK ADD CONSTRAINT [FK_TableP_tablea] FOREIGN KEY([reference_id])
REFERENCES [dbo].[TableA] ([mod_id])
GO
ALTER TABLE [dbo].[TableP] CHECK CONSTRAINT [FK_TableP_tablea]
GO
ALTER TABLE [dbo].[TableP] WITH CHECK ADD CONSTRAINT [FK_TableP_tableb] FOREIGN KEY([reference_id])
REFERENCES [dbo].[TableB] ([mod_id])
GO
ALTER TABLE [dbo].[TableP] CHECK CONSTRAINT [FK_TableP_tableb]
GO
Now add the edmx for the three tables, and your linq should look like this (use your dbcontext instead of BreazEntities22 :
var tableA = e.TableAs.
Where(w => w.TablePs.Any(s => s.module == "A")).ToList();
var tableB = e.TableBs.
Where(w => w.TablePs.Any(s => s.module == "A")).ToList();

Related

How to create a list of objects from 2 tables in KSQLDB

I currently have 2 tables in KSQLDB:
CREATE STREAM "source-mysql-person" (
"_uid" STRING,
"_created" TIMESTAMP,
"_updated" TIMESTAMP,
"_disabled" TIMESTAMP,
"name" STRING,
"age" INT
) WITH (
KAFKA_TOPIC = 'source-mysql-person',
VALUE_FORMAT = 'AVRO'
);
/*
Field | Type
--------------------------------------------
_uid | VARCHAR(STRING) (primary key)
_created | TIMESTAMP
_updated | TIMESTAMP
_disabled | TIMESTAMP
name | VARCHAR(STRING)
age | INTEGER
--------------------------------------------
*/
CREATE TABLE "table-mysql-enriched-person_contact" WITH (
KAFKA_TOPIC = 'table-mysql-enriched-person_contact',
VALUE_FORMAT = 'AVRO'
) AS SELECT
"pc"."_uid" AS "_uid",
"pc"."_created" AS "_created",
"pc"."_updated" AS "_updated",
"pc"."_disabled" AS "_disabled",
"pc"."is_default" AS "is_default",
"pc"."value" AS "value",
"pc"."person_uid" AS "person_uid",
AS_MAP(
ARRAY['_uid', 'value'],
ARRAY["ct"."_uid", "ct"."value"]
) AS "contact_type"
FROM "table-mysql-person_contact" "pc"
INNER JOIN "table-mysql-contact_type" "ct" ON
"ct"."_uid" = "pc"."contact_type_uid"
EMIT CHANGES;
/*
Field | Type
-----------------------------------------------
_uid | VARCHAR(STRING) (primary key)
_created | TIMESTAMP
_updated | TIMESTAMP
_disabled | TIMESTAMP
is_default | INTEGER
value | VARCHAR(STRING)
person_uid | VARCHAR(STRING)
contact_type | MAP<STRING, VARCHAR(STRING)>
-----------------------------------------------
*/
I want to create a table table-mysql-enriched-person that has the data of table-mysql-person and for each "person", a list of "person_contact" related to that "person". For this I am trying to use the following querie:
CREATE TABLE "table-mysql-enriched-person" WITH (
KAFKA_TOPIC = 'table-mysql-enriched-person',
VALUE_FORMAT = 'AVRO'
) AS SELECT
"p"."_uid" AS "_uid",
"p"."_created" AS "_created",
"p"."_updated" AS "_updated",
"p"."_disabled" AS "_disabled",
"p"."name" AS "name",
"p"."age" AS "age",
AS_MAP(
ARRAY[
'_uid',
'_created',
'_updated',
'_disabled',
'is_default',
'value',
'contact_type'
],
ARRAY[
"e"."_uid",
"e"."_created",
"e"."_updated",
"e"."_disabled",
"e"."is_default",
"e"."value",
"e"."contact_type"
]
) AS "list_person_contact"
FROM "table-mysql-enriched-person_contact" "e"
INNER JOIN "table-mysql-person" "p" ON
"p"."_uid" = "e"."person_uid"
GROUP BY
"p"."_uid",
"p"."_created",
"p"."_updated",
"p"."_disabled",
"p"."name",
"p"."age"
EMIT CHANGES;
Theoretically the query is correct because I have primary keys in the 2 queries and, thinking that the table "person_contact" is a child table of "person" and that the field person._uid is represented as person_contact.person_uid, I should manage to create the table but ksqldb is returning me the following message:
Could not determine output schema for query due to error: GROUP BY requires aggregate functions
in either the SELECT or HAVING clause.

Insert data in SQL Server stored procedure

I am trying to add data in single table using a SQL Server stored procedure and I am getting an error
procedure or function x has too many argument specified
Also how can I get newly created ID of record as I need to update multiple tables using these IDs
I am using SQL Server 2012
Many thanks
ALTER PROCEDURE [dbo].[CreateNewFunctionsNavigation]
#FunctionName nvarchar(250),
#Hierarchy_Level int
AS
BEGIN
SET NOCOUNT ON;
INSERT [dbo].[Navigation_Functions] ([FunctionName], [Hierarchy_Level])
VALUES(#FunctionName, #Hierarchy_Level)
END
Execution of stored procedure:
DECLARE #return_value int
EXEC #return_value = [dbo].[CreateNewFunctionsNavigation]
#FunctionName = N'DSD',
#Hierarchy_Level = 3
SELECT 'Return Value' = #return_value
GO
My SQL for Function table
USE [MySolution01_DB]
GO
/****** Object: Table [dbo].[Navigation_Functions] Script Date: 06/01/2015 15:58:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Navigation_Functions](
[Function_ID] [int] IDENTITY(1,1) NOT NULL,
[FunctionName] [nvarchar](250) NOT NULL,
[Hierarchy_Level] [int] NOT NULL,
CONSTRAINT [PK_Functions] PRIMARY KEY CLUSTERED
(
[Function_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
It should be
INSERT INTO [dbo].[Navigation_Functions] ([FunctionName], [Hierarchy_Level])
I created a sample table
CREATE TABLE [dbo].[Navigation_Functions](
[NavigationFunctionId] [int] IDENTITY(1,1) NOT NULL,
[FunctionName] [nvarchar](250) NULL,
[Hierarchy_Level] [int] NULL,
CONSTRAINT [PK_Navigation_Functions] PRIMARY KEY CLUSTERED
(
[NavigationFunctionId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
You can get the last ID by: SELECT SCOPE_IDENTITY();
USE [MySolution01_DB]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[CreateNewFunctionsNavigation]
#FunctionName nvarchar(250),
#Hierarchy_Level INT,
#Function_identity INT OUTPUT
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO [dbo].[Navigation_Functions] ([FunctionName],[Hierarchy_Level] )
VALUES(#FunctionName, #Hierarchy_Level);
SET #Function_identity=SCOPE_IDENTITY()
RETURN #Function_identity
RETURN
END

error line 86 for stored procedure

I am trying to get this stored procedure to work. I have been working for a month straight, was up till 3 last night, and am approaching burnout. I really want to get this to work as we have an ad campaign that we spent hundreds on sending traffic to.
USE [redhotkitties2005db]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[proc_rhkprod_lock_items_for_paypal]
#cfuseridid bigint
,#transaction_guid uniqueidentifier = NULL
AS
BEGIN
SET NOCOUNT ON;
declare #tblcartID bigint
,#cfuserid bigint
,#tblproductsid bigint
,#quantity bigint
,#localInventoryID varchar(100)
,#taxologykey bigint
,#name varchar(1000)
,#shortDescription varchar(8000)
,#productDescription varchar(8000)
,#UorLorUL varchar(2)
,#unitPrice money
,#shippingWeight numeric(6, 2)
,#overSize tinyint
,#smallPic1 nvarchar(100)
,#largePic1 nvarchar(100)
,#smallPic2 nvarchar(100)
,#largePic2 nvarchar(100)
,#smallPic3 nvarchar(100)
,#largePic3 nvarchar(100)
SET #transaction_guid = coalesce(#transaction_guid,newid())
declare c1 cursor forward_only for
select rhkProd_tblCart.tablePK AS tblcartID
,rhkProd_tblProducts.productID as tblproductsid
,rhkProd_tblCart.quantity
,rhkProd_tblProducts.localInventoryID
,rhkProd_tblProducts.name
,rhkProd_tblProducts.taxologyKey
,rhkProd_tblProducts.shortDescription
,rhkProd_tblProducts.productDescription
,rhkProd_tblProducts.UorLorUL
,rhkProd_tblProducts.unitPrice
,rhkProd_tblProducts.shippingWeight
,rhkProd_tblProducts.overSize
,rhkProd_tblProducts.smallPic1
,rhkProd_tblProducts.largePic1
,rhkProd_tblProducts.smallPic2
,rhkProd_tblProducts.largePic2
,rhkProd_tblProducts.smallPic3
,rhkProd_tblProducts.largePic3
from rhkProd_tblCart
INNER JOIN rhkProd_tblProducts
on rhkProd_tblCart.tblProductsFK = rhkProd_tblProducts.productID
where rhkProd_tblCart = #cfuserid
open c1
fetch next
from c1
into #tblcartID
,#cfuserid
,#tblproductsid
,#quantity
,#localinventoryID
,#name
,#taxologykey
,#shortdescription
,#productdescription
,#UorLorUL
,#unitprice
,#shippingweight
,#oversize
,#smallpic1
,#largepic1
,#smallpic2
,#largepic2
,#smallpic3
,#largepic3
begin
while ##fetch_status = 0
insert into rhkprod_tblpaypallock (
,[cfuserid]
,[transaction_guid]
,[timestamp]
,[tblproductsFK]
,[quantity]
,[localInventoryID]
,[name]
,[taxologykey]
,[shortdescription]
,[productdescription]
,[uorlorul]
,[unitprice]
,[shippingweight]
,[oversize]
,[smallpic1]
,[largepic1]
,[smallpic2]
,[largepic2]
,[smallpic3]
,[largepic3]
)
values (
,#cfuserid
,#transaction_guid
,getdate()
,#tblproductsid
,#quantity
,#localinventoryID
,#name
,#taxologykey
,#shortdescription
,#productdescription
,#UorLorUL
,#unitprice
,#shippingweight
,#oversize
,#smallpic1
,#largepic1
,#smallpic2
,#largepic2
,#smallpic3
,#largepic3
)
update rhkprod_tblproducts
set quantity = quantity - #quantity
where productid = #tblproductsid
and UorLorUL in ('U','L')
fetch next
from c1
into #tblcartID
,#cfuserid
,#tblproductsid
,#quantity
,#localinventoryID
,#name
,#taxologykey
,#shortdescription
,#productdescription
,#UorLorUL
,#unitprice
,#shippingweight
,#oversize
,#smallpic1
,#largepic1
,#smallpic2
,#largepic2
,#smallpic3
,#largepic3
close c1
deallocate c1
end
END
Your INSERT statement has a stray comma at the start:
insert into rhkprod_tblpaypallock (
,[cfuserid]
Should be
insert into rhkprod_tblpaypallock (
[cfuserid]
Your VALUES clause also has a stray comma:
values (
,#cfuserid
Should be
values (
#cfuserid

How to create simple membership sql tables manually?

I'm looking for a tool similar to Aspnet_regsql.exe for ASP .NET Membership just for simpleMemberShip Provider. Creating the tables at runtime is too late, cause a client program uses the same tables.
UserProfile
webpages_Membership
webpages_OAuthMembership
webpages_Roles
webpages_UsersInRoles
Any advice would be great
You could just create the script yourself, using SQL Management Studio, after running your application on your developer machine:
Example follows from a similar task I did (note dates, not sure if anything has changed).
Note: you'll need to create the database and do the normal permission setup etc as you would do for any production system.
/****** Object: Table [dbo].[UserProfile] Script Date: 12/06/2012 18:18:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[UserProfile](
[UserId] [int] IDENTITY(1,1) NOT NULL,
[UserName] [nvarchar](56) NOT NULL,
PRIMARY KEY CLUSTERED
(
[UserId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
UNIQUE NONCLUSTERED
(
[UserName] 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
/****** Object: Table [dbo].[webpages_Membership] Script Date: 12/06/2012 18:18:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[webpages_Membership](
[UserId] [int] NOT NULL,
[CreateDate] [datetime] NULL,
[ConfirmationToken] [nvarchar](128) NULL,
[IsConfirmed] [bit] NULL,
[LastPasswordFailureDate] [datetime] NULL,
[PasswordFailuresSinceLastSuccess] [int] NOT NULL,
[Password] [nvarchar](128) NOT NULL,
[PasswordChangedDate] [datetime] NULL,
[PasswordSalt] [nvarchar](128) NOT NULL,
[PasswordVerificationToken] [nvarchar](128) NULL,
[PasswordVerificationTokenExpirationDate] [datetime] NULL,
PRIMARY KEY CLUSTERED
(
[UserId] 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].[webpages_Membership] ADD DEFAULT ((0)) FOR [IsConfirmed]
GO
ALTER TABLE [dbo].[webpages_Membership] ADD DEFAULT ((0)) FOR [PasswordFailuresSinceLastSuccess]
GO
/****** Object: Table [dbo].[webpages_OAuthMembership] Script Date: 12/06/2012 18:19:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[webpages_OAuthMembership](
[Provider] [nvarchar](30) NOT NULL,
[ProviderUserId] [nvarchar](100) NOT NULL,
[UserId] [int] NOT NULL,
PRIMARY KEY CLUSTERED
(
[Provider] ASC,
[ProviderUserId] 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
/****** Object: Table [dbo].[webpages_Roles] Script Date: 12/06/2012 18:19:26 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[webpages_Roles](
[RoleId] [int] IDENTITY(1,1) NOT NULL,
[RoleName] [nvarchar](256) NOT NULL,
PRIMARY KEY CLUSTERED
(
[RoleId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
UNIQUE NONCLUSTERED
(
[RoleName] 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
/****** Object: Table [dbo].[webpages_UsersInRoles] Script Date: 12/06/2012 18:19:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[webpages_UsersInRoles](
[UserId] [int] NOT NULL,
[RoleId] [int] NOT NULL,
PRIMARY KEY CLUSTERED
(
[UserId] ASC,
[RoleId] 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].[webpages_UsersInRoles] WITH CHECK ADD CONSTRAINT [fk_RoleId] FOREIGN KEY([RoleId])
REFERENCES [dbo].[webpages_Roles] ([RoleId])
GO
ALTER TABLE [dbo].[webpages_UsersInRoles] CHECK CONSTRAINT [fk_RoleId]
GO
ALTER TABLE [dbo].[webpages_UsersInRoles] WITH CHECK ADD CONSTRAINT [fk_UserId] FOREIGN KEY([UserId])
REFERENCES [dbo].[UserProfile] ([UserId])
GO
ALTER TABLE [dbo].[webpages_UsersInRoles] CHECK CONSTRAINT [fk_UserId]
GO

Linq to Entity with multiple left outer joins

I am trying to understand left outer joins in LINQ to Entity. For example I have the following 3 tables:
Company, CompanyProduct, Product
The CompanyProduct is linked to its two parent tables, Company and Product.
I want to return all of the Company records and the associated CompanyProduct whether the CompanyProduct exists or not for a given product. In Transact SQL I would go from the Company table using left outer joins as follows:
SELECT * FROM Company AS C
LEFT OUTER JOIN CompanyProduct AS CP ON C.CompanyID=CP.CompanyID
LEFT OUTER JOIN Product AS P ON CP.ProductID=P.ProductID
WHERE P.ProductID = 14 OR P.ProductID IS NULL
My database has 3 companies, and 2 CompanyProduct records assocaited with the ProductID of 14. So the results from the SQL query are the expected 3 rows, 2 of which are connected to a CompanyProduct and Product and 1 which simply has the Company table and nulls in the CompanyProduct and Product tables.
So how do you write the same kind of join in LINQ to Entity to acheive a similiar result?
I have tried a few different things but can't get the syntax correct.
Thanks.
Solved it!
Final Output:
theCompany.id: 1
theProduct.id: 14
theCompany.id: 2
theProduct.id: 14
theCompany.id: 3
Here is the Scenario
1 - The Database
--Company Table
CREATE TABLE [theCompany](
[id] [int] IDENTITY(1,1) NOT NULL,
[value] [nvarchar](50) NULL,
CONSTRAINT [PK_theCompany] 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
--Products Table
CREATE TABLE [theProduct](
[id] [int] IDENTITY(1,1) NOT NULL,
[value] [nvarchar](50) NULL,
CONSTRAINT [PK_theProduct] 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
--CompanyProduct Table
CREATE TABLE [dbo].[CompanyProduct](
[fk_company] [int] NOT NULL,
[fk_product] [int] NOT NULL
) ON [PRIMARY];
GO
ALTER TABLE [CompanyProduct] WITH CHECK ADD CONSTRAINT
[FK_CompanyProduct_theCompany] FOREIGN KEY([fk_company])
REFERENCES [theCompany] ([id]);
GO
ALTER TABLE [dbo].[CompanyProduct] CHECK CONSTRAINT
[FK_CompanyProduct_theCompany];
GO
ALTER TABLE [CompanyProduct] WITH CHECK ADD CONSTRAINT
[FK_CompanyProduct_theProduct] FOREIGN KEY([fk_product])
REFERENCES [dbo].[theProduct] ([id]);
GO
ALTER TABLE [dbo].[CompanyProduct] CHECK CONSTRAINT
[FK_CompanyProduct_theProduct];
2 - The Data
SELECT [id] ,[value] FROM theCompany
id value
----------- --------------------------------------------------
1 company1
2 company2
3 company3
SELECT [id] ,[value] FROM theProduct
id value
----------- --------------------------------------------------
14 Product 1
SELECT [fk_company],[fk_product] FROM CompanyProduct;
fk_company fk_product
----------- -----------
1 14
2 14
3 - The Entity in VS.NET 2008
alt text http://i478.photobucket.com/albums/rr148/KyleLanser/companyproduct.png
The Entity Container Name is 'testEntities' (as seen in model Properties window)
4 - The Code (FINALLY!)
testEntities entity = new testEntities();
var theResultSet = from c in entity.theCompany
select new { company_id = c.id, product_id = c.theProduct.Select(e=>e) };
foreach(var oneCompany in theResultSet)
{
Debug.WriteLine("theCompany.id: " + oneCompany.company_id);
foreach(var allProducts in oneCompany.product_id)
{
Debug.WriteLine("theProduct.id: " + allProducts.id);
}
}
5 - The Final Output
theCompany.id: 1
theProduct.id: 14
theCompany.id: 2
theProduct.id: 14
theCompany.id: 3
IT should be something like this....
var query = from t1 in db.table1
join t2 in db.table2
on t1.Field1 equals t2.field1 into T1andT2
from t2Join in T1andT2.DefaultIfEmpty()
join t3 in db.table3
on t2Join.Field2 equals t3.Field3 into T2andT3
from t3Join in T2andT3.DefaultIfEmpty()
where t1.someField = "Some value"
select
{
t2Join.FieldXXX
t3Join.FieldYYY
};
This is how I did....
You'll want to use the Entity Framework to set up a many-to-many mapping from Company to Product. This will use the CompanyProduct table, but will make it unnecessary to have a CompanyProduct entity set in your entity model. Once you've done that, the query will be very simple, and it will depend on personal preference and how you want to represent the data. For example, if you just want all the companies who have a given product, you could say:
var query = from p in Database.ProductSet
where p.ProductId == 14
from c in p.Companies
select c;
or
var query = Database.CompanySet
.Where(c => c.Products.Any(p => p.ProductId == 14));
Your SQL query returns the product information along with the companies. If that's what you're going for, you might try:
var query = from p in Database.ProductSet
where p.ProductId == 14
select new
{
Product = p,
Companies = p.Companies
};
Please use the "Add Comment" button if you would like to provide more information, rather than creating another answer.
LEFT OUTER JOINs are done by using the GroupJoin in Entity Framework:
http://msdn.microsoft.com/en-us/library/bb896266.aspx
The normal group join represents a left outer join. Try this:
var list = from a in _datasource.table1
join b in _datasource.table2
on a.id equals b.table1.id
into ab
where ab.Count()==0
select new { table1 = a,
table2Count = ab.Count() };
That example gives you all records from table1 which don't have a reference to table2.
If you omit the where sentence, you get all records of table1.
Please try something like this:
from s in db.Employees
join e in db.Employees on s.ReportsTo equals e.EmployeeId
join er in EmployeeRoles on s.EmployeeId equals er.EmployeeId
join r in Roles on er.RoleId equals r.RoleId
where e.EmployeeId == employeeId &&
er.Status == (int)DocumentStatus.Draft
select s;
Cheers!
What about this one (you do have a many-to-many relationship between Company and Product in your Entity Designer, don't you?):
from s in db.Employees
where s.Product == null || s.Product.ProductID == 14
select s;
Entity Framework should be able to figure out the type of join to use.

Resources