I have a main table called M1 which consists of Ids of three individual tables T1,T2 and T3.
I need to join 3 tables onto M1 using their Ids and display their Names
For this I am using the following query:
var query= (from i in dbContext.M1
join j in dbContext.T1 on i.Mt1_id equals j.Mt1_id
join l in dbContext.T2 on i.Mt2_id equals l.Mt2_id
join s in dbContext.T3 on i.Mt3_id equals s.Mt3_id
where i.Mid >= 1
select new
{
a=j.name,
b=l.name,
c=s.name
}).ToArray();
I have used this way, but I am getting an error stating that "Type inference failed in call to Join"
Could any one please tell me where I went wrong?
Please check Datatype of columns to avoid "Type inference failed in call to Join" exception
Related
My issue seems to be simple, but I can't figure out what's happening.
I have the following LINQ query:
(from p in db.VW_PROJETOS
join ic in db.vw_InstanciaCarteira
on p.CodigoProjeto equals ic.CodigoProjeto
where ic.CodigoCarteira == 125
orderby p.CodigoProjeto
select p).ToList();
It returns 9 entries from VW_PROJETOS, such as IDs, FKs, string, dates... If I execute same query in SQL Server Management Studio, as the following
select * from VW_PROJETOS p
inner join vw_InstanciaCarteira ic on p.CodigoProjeto = ic.CodigoProjeto
where ic.CodigoCarteira = 125
order by p.CodigoProjeto
it will return the same 9 entries, with the same data for each entry, except for column "Desempenho". Here's a short example:
SQL Server returns:
CodigoProjeto NomeProjeto Desempenho
13 Projeto 1 Satisfatório
1247 Projeto 2 NULL
1435 Projeto 3 Crítico
LINQ query returns:
CodigoProjeto NomeProjeto Desempenho
13 Projeto 1 Crítico
1247 Projeto 2 Crítico
1435 Projeto 3 Satisfatório
I saw some examples of using ROW_NUMBER to create indexes for the views, in order to help LINQ to not loses itself when working with views, but I couldn't make it work right (the index that was shown in SQL query was always different from the index that LINQ returns).
Is this a common issue? Is it easy to correct or workaround? It can be an error in the View itself?
EDIT:
Following some of your advices, I checked the relation between unique keys and fields in Entity Framework entities. I put several keys, properly ordered, in both EF entities, but the result was the same. I got the SQL query generated by my LINQ and it gives exactly the same result as the one I posted above. I've also generated the models again, using Code-First from Database, in order to have keys ordered by the code generation, and it was useless as well.
Use this query.
(from p in db.VW_PROJETOS
join ic in db.vw_InstanciaCarteira
on p.CodigoProjeto equals ic.CodigoProjeto
where ic.CodigoCarteira == 125
orderby p.CodigoProjeto
select new {
CodigoProjeto=p.CodigoProjeto,
NomeProjeto=p. NomeProjeto,
Desempenho=ic.Desempenho
}.ToList();
Check the data type for the column "CodigoProjeto" in both db.vw_InstanciaCarteira and db.VW_PROJETOS. They should match.
I have two DataTables with different data,common columns in both are quantity and Itemcode. I want to join the two tables together where two fields, (DataTable1.itemcode=DataTable2.itemcode) AND (DataTable1.quantity=DataTable2.quantity) OR ((DataTable1.quantity+1)=DataTable2.quantity) OR ((DataTable1.quantity+2)=DataTable2.quantity) . How would I write this in LINQ?
if item code is same and quantity is equal,exceeds by 1 or 2 then I should get joined result.
I tried using anonymous objects but that is for AND condition and OR condition was not fulfilled,so only itemcode and any one of these conditions was achieved at a time?
Please suggest me the correct way to do it?
You have to use the following syntax to access fields of the dataset:
[DataTable Name].Field<string>(indexNo or ColumnName)
So you can write the following linq to put a join between two data tables:
from t1 in dataTable.AsEnumerable()
//join between two tables
join t2 in dataTable2.AsEnumerable() on t1.Field<string>(0) equals t2.Field<string>(0)
//where conditions
where t1.Field<string>(0) == [value]
//select clause
select t1.Field<string>(colmNo)
Also you can convert the two data tables to IEnumerable by creating extension method.
I want to join 2 tables and get some data out of it using LINQ. here are the 2 ways in which i can do this
1.
var orders = from order in db.Order
from user in db.User
where order.UserId == user.UserId
select order;
2.
var result = from order in db.Order
join user in db.user
on order.UserId equals user.userId
select order
are these queries one and the same? are they different in any way?
Both are same. First syntax is implicit, second one is explicit join syntax.
Refer to wikipedia link for both type of syntax.
I've a question about a SQL query.. I'm building a prototype webshop in ASP.NET Visual Studio. Now I'm looking for a solution to view my products. I've build a database in MS Access, it consists of multiple tables.
The tables which are important for my question are:
Product
Productfoto
Foto
Below you'll see the relations between the tables
For me it is important to get three datatypes: Product title, price and image.
The product title, and the price are in the Product table. The images are in the Foto table.
Because a product can have more than one picture, there is a N - M relation between them. So I've to split it up, I did it in the Productfoto table.
So the connection between them is:
product.artikelnummer -> productfoto.artikelnummer
productfoto.foto_id -> foto.foto_id
Then I can read the filename (in the database: foto.bestandnaam)
I've created the first inner join, and tested it in Access, this works:
SELECT titel, prijs, foto_id
FROM Product
INNER JOIN Productfoto
ON product.artikelnummer = productfoto.artikelnummer
But I need another INNER JOIN, how could I create that? I guess something like this (this one will give me an error)
SELECT titel, prijs, bestandnaam
FROM Product
(( INNER JOIN Productfoto ON product.artikelnummer = productfoto.artikkelnummer )
INNER JOIN foto ON productfoto.foto_id = foto.foto_id)
Can anyone help me?
something like this should work:
SELECT Product.titel, Product.prijs, Foto.bestandnaam FROM Product INNER JOIN
(Foto INNER JOIN Productfoto ON Foto.[foto_id] = Productfoto.[foto_id]) ON
Product.[artikelnummer] = Productfoto.[artikelnummer];
One thing about the use of linking tables
The ProductFoto table allows for N-M relations between Product and Foto indeed. Is this what you really want/need? In other words, can one Foto belong to more than one Product? If not, put the Product_Id on the Foto table. If so,...
...let's discuss JOIN.
Say we have two tables, A and B. doing a
SELECT * FROM A, B
will give you all permutations of A's rows with B's rows. We could limit the resultset by adding a WHERE clause, like WHERE A.a='lekker hoor!', or a way cooler WHERE A.id=B.a_id. Which actually starts to look like a JOIN result!
Lets do a proper JOIN then:
SELECT * FROM A JOIN B ON A.id=B.a_id
JOINs actually come in LEFT OUTER, RIGHT OUTER and FULL INNER or FULL OUTER joins.
A LEFT JOIN (use of OUTER is optional) will contain all records in the left (first) table, even if there is no corresponding records(s) in the right (second) table.
A RIGHT JOIN obviously works the same way, but mirrored.
With a FULL OUTER JOIN both tables are optional (not quite the same as SELECT * FROM A, B though!).
A FULL INNER needs matching records from both tables (this is the default).
When you do want to do more than one JOIN, say
SELECT * FROM
A
JOIN B ON A.id=B.a_id
JOIN C ON B.id=C.b_id
You can think of the extra JOIN as joining on an intermediate table, formed by joining A and B, especially when mixing some LEFT/RIGHT/INNER/OUTER JOINs.
As to your question
Use something along the lines of
SELECT TOP (1) titel, prijs, bestandnaam
FROM
( -- this bracket is MS Access specific (and awkward)
Product
INNER JOIN Productfoto ON product.artikelnummer = productfoto.artikelnummer
) -- this one too
INNER JOIN foto ON productfoto.foto_id = foto.foto_id
to satisfy MS Access, use brackets around first two tables, see Ms-Access: Join 3 Tables
Normally no brackets required (you'll get to use them like this when you discover sexy sub-selects, for which the rule is: only use them if there is no alternative).
Because there are multiple matches in your ProductFoto table, there are multiple matches in your result. Use TOP 1 (or LIMIT 1, depending on your DB) to 'fix' this.
Veel success, en doe jezelf een plezier en switch to English!
1) First issue I'm having is if you do an include and then an order by the SQL generated generates an inner join and an outer join
var query = from l in Lead.Include("Contact")
orderby l.Contact.FirstName
select l;
Which generates the following inner join and outer join on the same table
INNER JOIN [dbo].[Contact] AS [Extent2]
ON [Extent1].[ContactId] = [Extent2].[ContactId]
LEFT OUTER JOIN [dbo].[Contact] AS [Extent3]
ON [Extent1].[ContactId] = [Extent3]. [ContactId]
ORDER BY [Extent2].[FirstName] ASC
Which makes for a slightly inefficient query
2) if I do multiple includes it always does the second one as an outer join so like
Lead.Include("OneToOne").Include("OtherOneToOne") <- in this scenario
OtherOneToOne is an outer
join and OneToOne is an inner
join
Lead.Include("OtherOneToOne").Include("OneToOne") <- in this scenario
OneToOne is an outer join
and OtherOneToOne is an
inner join
is that just how it works?
I found another post where someone was talking about this and they said that it was fixed in the June CTP release
http://blogs.msdn.com/b/adonet/archive/2011/06/30/announcing-the-microsoft-entity-framework-june-2011-ctp.aspx
But I installed and setup that to be used and it still doesn't work..
alright it won't let me answer my own question
so
EDIT:
Alright I setup an isolated test and found that http://blogs.msdn.com/b/adonet/archive/2011/06/30/announcing-the-microsoft-entity-framework-june-2011-ctp.aspx seems to have resolved these
But since I'm using RIA I'm out of luck since the june ctp doesn't support RIA :-/
A solution is to do the include yourself:
var query = from l in Lead
select new { l, l.Contact } into row
orderby row.Contact.FirstName
select row;