C# Linq select all columns but alias a couple - c#

I have the following query:
var list = (
from au in context.AnagraficaUtenti
join ut in context.Utenti on au.CodiceUtente equals ut.CodiceUtente into allcolumns
from entry in allcolumns
select entry
)
.ToList();
the problem is that both AnagraficaUtenti and Utenti have two columns called "Name" and "Surname", so the list I get contains only one of them. I would like to obtain a list of objects whose fields will be "NameAnagraficaUtenti", "SurnameAnagraficUtenti", "NameUtenti" and "SurnameUtenti" (among all the others).
Is that possible? Thank you.
P.S. I know that I can select fields one by one, by doing something like "new {field1 = field1, field2 = field2}", but I'd love if I could accomplish the same result with a general "select all", thank you.

Related

While Selecting based on ROWID - Distinct or Group By doesn't work in oracle

I have query like below , I tried to filter out duplicate columns by using Group BY
SELECT contacts.rowid AS ROW_PASS,
duty_rota.rowid AS ROW_PASS_ROTA,
duty_rota.duty_type AS DUTY_TYPE
FROM duty_rota,
duty_types,
contacts
WHERE duty_rota.duty_type = duty_types.duty_type
AND duty_rota.duty_officer = contacts.duty_id
AND sname IS NOT NULL
GROUP BY contacts.rowid,
duty_rota.rowid,
duty_rota.duty_type
ORDER BY duty_date
After playing with the query little bit I came to know we can't filter out distinct using group by while using ROWID. So can somebody please help me to write code (in SQL) with a logic that
if (any row is completely identical with another row of the query o/p)
{
then display only one column
}
I will be using the output as gridview's data source in C#, so if not in SQL - can you help me whether somehow in C# I can achieve to display only identical columns?
If you want to filter duplicate rows, you can use this query:
SELECT Max(duty_rota.rowid) AS ROW_PASS_ROTA,
duty_rota.duty_type AS DUTY_TYPE
FROM duty_rota,
duty_types,
contacts
WHERE duty_rota.duty_type = duty_types.duty_type
AND duty_rota.duty_officer = contacts.duty_id
AND sname IS NOT NULL
GROUP BY duty_rota.duty_type
ORDER BY DUTY_TYPE
Here you go: http://sqlfiddle.com/#!2/2a038/2
Take out the ROWID's. Example: If your table has 3 columns (colA, colB, colC) you could find exact row dups this way...
select a.* from
(
select count(*) dupCnt, colA, colB, colC from myTable
group by colA, colB, colC
) a
where dupCnt > 1
First, the ROWID is a unique field for each row, so using this field you will never have duplicates. The only solution here is to not use it. It's data does not hold anything you would want to display anyway.
Simply put, if you want no duplicates, you need the DISTINCT keyword:
SELECT DISTINCT field1,
field2
FROM table1,
table2
WHERE table1.key1 = table2.key1;
This will select all Field1, Field2 combinations from the two tables. Due to the DISTINCT keyword, each line will only be in the result list once. Duplicates will not be in the result list.
SELECT DISTINCT duty_rota.duty_type AS DUTY_TYPE
FROM duty_rota,
duty_types,
contacts
WHERE duty_rota.duty_type = duty_types.duty_type
AND duty_rota.duty_officer = contacts.duty_id
AND sname IS NOT NULL
ORDER BY duty_date
You will only need to GROUP BY if you need further operations on the result set, like counting the duplicates. If all you need is "no duplicates", the DISTINCT keyword is exactly what you are looking for.
Edit:
In case I misread your question and you want to see only those, that are duplicates, you need to group and you need to filter based on the groups criteria. You can do that using the HAVING clause. It's kind of an additional WHERE of the groups criteria:
SELECT FIELD1, FIELD2, COUNT(*)
FROM TABLE1, TABLE2
WHERE TABLE1.KEY1 = TABLE2.KEY1
GROUPB BY FIELD1, FIELD2
HAVING COUNT(*) > 1

How to select Distinct names from a xml database using LINQ?

i am trying this query to get all the city's
var queryAllCustomers = from cust in loadedCustomData.Descendants("record")
select (string)cust.Element("City") ;
so it returns all city's including repeated, but i only want to get distinct city i.e to repeat only ones so how to achieve that?
Use Distinct Extension Method
var queryAllCustomers = (from cust in loadedCustomData.Descendants("record")
select (string)cust.Element("City")).Distinct();

How to make UNION of 2 SELECT statement

This is my query:
string x1 = "SELECT unos_golub.drzava, unos_golub.spol, unos_golub.broj_goluba as broj, parovi.par_m, parovi.par_z,parovi.broj_para FROM parovi JOIN unos_golub ON (parovi.par_m=unos_golub.ID) WHERE parovi.uzgojni_par=1";
string x2 = "SELECT unos_golub.drzava, unos_golub.spol, unos_golub.broj_goluba as broj2, parovi.par_m, parovi.par_z,parovi.broj_para FROM parovi JOIN unos_golub ON (parovi.par_z=unos_golub.ID) WHERE parovi.uzgojni_par=1 ORDER BY broj_para ASC";
cmd.CommandText = x1+" UNION ALL "+x2;
In my table "parovi" there are 2 columns "par_m" and "par_z".
In second table "unos_golub" there is "ID" and some other. Now I need to get values from "par_m" and "par_z", match it in "unos_golub" and get some data.
For example, if I get par_m=91 and par_z=92, I need to find those numbers in ID of "unos_golub" and get different data for 91 and 92 and show it.
I think maybe UNION ALL could help, but it is not working.
here are my tables
table: parovi
table: unos_golub
This approach will put all on a single row for the respective "M" and "Z" values. Notice I'm joining TWICE to the "unos_golub" table, but with different aliases. So, now I have one parovi record pointing to respective "M" AND "Z" versions simultaneously. And can pull the columns from each, thus giving them aliased result column names suffixing "M" and "Z" indicating their respective origin.
SELECT
parovi.par_m,
parovi.par_z,
parovi.broj_para,
unos_M.drzava as drzava_M,
unos_M.spol as spol_M,
unos_M.broj_goluba as broj_M,
unos_Z.drzava as drzava_Z,
unos_Z.spol as spol_Z,
unos_Z.broj_goluba as broj_Z
FROM
parovi
JOIN unos_golub as unos_M
ON parovi.par_m = unos_M.ID
JOIN unos_golub as unos_Z
ON parovi.par_m = unos_Z.ID
WHERE
parovi.uzgojni_par=1";
Per your comment of wanting to show all rows, your query SHOULD only require one small change. When doing a UNION, the queries must have the same column names. You changed one o them via
unos_golub.broj_goluba as broj
vs
unos_golub.broj_goluba as broj2
which would make it fail the query. The column names are different, thus failing.

Linq Query to Get Distinct Records from Two Tables

I have two Tables - tblExpenses and tblCategories as follows
tblExpenses
ID (PK),
Place,
DateSpent,
CategoryID (FK)
tblCategory
ID (PK),
Name
I tried various LINQ approaches to get all distinct records from the above two tables but not with much success. I tried using UNION and DISTINCT but it didnt work.
The above two tables are defined in my Model section of my project which in turn will create tables in SQLite. I need to retrieve all the distinct records from both the tables to display values in gridview.
Kindly provide me some inputs to accomplish this task. I did some research to find answer to this question but nothing seemed close to what I wanted. Excuse me if I duplicated this question.
Here is the UNION, DISTINCT approaches I tried:
DISTINCT # ==> Gives me Repetitive values
(from exp in db.Table<tblExpenses >()
from cat in db.Table<tblCategory>()
select new { exp.Id, exp.CategoryId, exp.DateSpent, exp.Expense, exp.Place, cat.Name }).Distinct();
UNION # ==> Got an error while using UNION
I think union already does the distict when you join the two tables you can try somethin like
var query=(from c in db.tblExpenses select c).Concat(from c in
db.tblCategory select c).Distinct().ToList();
You will always get DISTINCT records, since you are selecting the tblExpenses.ID too. (Unless there are multiple categories with the same ID. But that of course would be really, really bad design.)
Remember, when making a JOIN in LINQ, both field names and data types should be the same. Is the field tblExpenses.CategoryID a nullable field?
If so, try this JOIN:
db.Table<tblExpenses>()
.Join(db.Table<tblCategory>(),
exp => new { exp.CategoryId },
cat => new { CategoryId = (int?)cat.ID },
(exp, cat) => new {
exp.Id,
exp.CategoryId,
exp.DateSpent,
exp.Expense,
exp.Place,
cat.Name
})
.Select(j => new {
j.Id,
j.CategoryId,
j.DateSpent,
j.Expense,
j.Place,
j.Name
});
You can try this queries:
A SELECT DISTINCT query like this:
SELECT DISTINCT Name FROM tblCategory INNER JOIN tblExpenses ON tblCategory.categoryID = tblExpenses.categoryID;
limits the results to unique values in the output field. The query results are not updateable.
or
A SELECT DISTINCTROW query like this:
SELECT DISTINCTROW Name FROM tblCategory INNER JOIN tblExpenses ON tblCategory.categoryID = tblExpenses.categoryID;<br/><br/>
looks at the entire underlying tables, not just the output fields, to find unique rows.
reference:http://www.fmsinc.com/microsoftaccess/query/distinct_vs_distinctrow/unique_values_records.asp

asp.net Ado stored procedure fields

I have the following select in an stored procedure:
Select I.ID,
I.Name,
I.NameUrl,
I.Teaser,
I.Description,
I.Coords,
I.Banned,
I.DateAdded,
I.TypeID,
I.MainCategoryID,
C.Name,
C.NameUrl,
C.Description
from Items I
inner join Categories C on C.ID=I.MainCategoryID
Some of the columns in few tables have the same name.
The asp.net ADO code below doesnt work for this equal names that im using.
My question is: Do i have to give a name, in the sql query, to the fields C.Name, C.NameUrl and C.Description in order to get it from the datatable indicated below? I Mean, i would like to avoid to put (in every stored procedure) the "C.Name as CategoryName", "C.ID as CategoryID", etc... Do you know a solution?
item.Name = Convert.ToString(dt.Rows[0]["Name"]);
item.NameUrl = Convert.ToString(dt.Rows[0]["NameUrl"]);
item.Teaser = Convert.ToString(dt.Rows[0]["Teaser"]);
item.Description = Convert.ToString(dt.Rows[0]["Description"]);
item.DateAdded = Convert.ToDateTime(dt.Rows[0]["DateAdded"]);
item.IsBanned = Convert.ToBoolean(dt.Rows[0]["Banned"]);
item.MainCategory = new Category();
item.MainCategory.ID = Convert.ToInt32(dt.Rows[0]["MainCategoryID"]);
item.MainCategory.Name = Convert.ToString(dt.Rows[0]["C.Name"]);
item.MainCategory.NameUrl= Convert.ToString(dt.Rows[0]["C.NameUrl"]);
Thanks in advance.
Regards.
Jose
You can use the column name from the result set without the qualifier.
However, you have ambiguous column names. So you need to alias them:
Select I.ID,
I.Name AS ItemName,
I.NameUrl AS ItemNameUrl,
I.Teaser,
I.Description AS ItemNDescription,
I.Coords,
I.Banned,
I.DateAdded,
I.TypeID,
I.MainCategoryID,
C.Name AS CategoryName,
C.NameUrl AS CategoryNameUrl,
C.Description AS CategoryDescription
from Items I
inner join Categories C on C.ID=I.MainCategoryID
and
item.Name = Convert.ToString(dt.Rows[0]["ItemName"]);
item.NameUrl = Convert.ToString(dt.Rows[0]["ItemNameUrl"]);
item.Teaser = Convert.ToString(dt.Rows[0]["Teaser"]);
item.Description = Convert.ToString(dt.Rows[0]["ItemDescription"]);
item.DateAdded = Convert.ToDateTime(dt.Rows[0]["DateAdded"]);
item.IsBanned = Convert.ToBoolean(dt.Rows[0]["Banned"]);
item.MainCategory = new Category();
item.MainCategory.ID = Convert.ToInt32(dt.Rows[0]["MainCategoryID"]);
item.MainCategory.Name = Convert.ToString(dt.Rows[0]["C.CategoryName"]);
item.MainCategory.NameUrl= Convert.ToString(dt.Rows[0]["C.CategoryNameUrl"]);
item.MainCategory.Description= Convert.ToString(dt.Rows[0]["C.CategoryDescription"]);
...
The solution would be to refactor your database to use the right column names. Without refactoring your database, you will have to refactor your stored procedures to correctly identify the columns.
Either way, you are in for quite a bit of typing.
It will be better if you do aliasing, otherwise it will always give problem
Select I.ID,
I.Name as IName,
I.NameUrl,
I.Teaser,
I.Description as Idescription,
I.Coords,
I.Banned,
I.DateAdded,
I.TypeID,
I.MainCategoryID,
C.Name as CName,
C.NameUrl,
C.Description as Cdescription from Items I
inner join Categories C on C.ID=I.MainCategoryID
Probably use an alias for the same naming column like
Select I.ID,
I.Name as itemname,
I.NameUrl as itemurl,
I.Teaser,
I.Description as itemdesc,
I.Coords,
I.Banned,
I.DateAdded,
I.TypeID,
I.MainCategoryID,
C.Name as catname,
C.NameUrl as caturl,
C.Description as catdesc
from Items I inner join Categories C on C.ID=I.MainCategoryI
As a few others have said, you'll need to alias the names in your Stored Procedure and they have given you examples on how to do so. Alternatively, you can SELECT INTO a temp table and name them what you would like and then have your code pull from the temp table without any aliasing needed on the code-side. However, there is no getting around having to alias the stored procedure. Good Luck!

Categories

Resources