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!
Related
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.
I'm brand new to .net MVC, and while I have some basic experience with writing SQL queries, I'm not sure how to go about what I need to do for .NET.
My initial query looks like this:
var results = (from s in db.Members
join sa in db.FocusArea on s.ID equals sa.MemberID
where sa.Area == SearchString
select new { s.ID, s.Name, s.Overview }).ToList();
This is not functioning correctly. It is seaching in the s.Overview for some reason. And, I need to make this query much more complicated. In short, I have three tables I need to search across. And with this query, it is not working:
var conceptResults = (from s in db.Cohorts
join oa in db.OutcomeArea on s.ID equals oa.CohortID
where ((oa.Area.Contains(SearchString))
|| (oa.OutcomeType.Contains(SearchString)))
select new { s.ID, s.Name, s.Overview }).ToList();
I need to use my SearchString to search for matches in both Area and Description in db.FocusArea.
I also need to use my SearchString to search for matches (contains) in another table db.SpecificFocusAreas for column SFocusArea where again the join is the ID/MemberID.
Is there a way to essentially do a join or join type of statement? I don't want to join all three tables because I am looking for results from either of the two joins, not from all joins.
I have a table say Category with the following fields:
cat_id, cat_name and Cat_desc
I also have another table product with the following fields:
pro_id, cat_id, pro_name and pro_desc, is_finished
Ordinarily, if I select a category with Linq to sql, it returns the category with all the associated products.
But I want to select a category but the products returned should be only product with is_finished value that is true.
any suggestion/code sample will be appreciated.
You need to join the tables:
select * from product p
left join Category c on c.cat_id = p.cat_id
where c.cat_name = 'yourcategory' and p.is_finished = 1
In linq to SQL:
var query = from product in products
join category in categories on category.cat_id = product.cat_id
select new { product.is_finished = true, category.cat_name = "yourcategory" };
This is probably the wisest way to do what you're asking:
var query = from product in products
select new {
product,
finishedCategories = product.categories.Where(c => c.is_finished)
};
This creates an anonymous type that has the data you're looking for. Note that if you access .product.categories you'll still get all of that product's categories (lazily-loaded). But if you use .finishedCategories you'll just get the categories that were finished.
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
I have a Category table with a tree structure (Id,MasterId)
I'd like to select all products that belong to a Category and all Child Categories.
Today I use this SQL Query which works, but I'd like to add pagination and that would be easier with a pure LINQ query. I use Entity Framework 4.
#Count int = 100,
#CategoryId int
with mq as
(
select c.Id as parent, c.Id as child
from dbo.Categories c
where c.Id = #CategoryId
union all
select q.child, c.Id
from mq q
inner join dbo.Categories c on q.child = c.MasterId
)
select top (#Count) P.* from Products P
inner join ProductToCategory PC ON(PC.ProductId = P.Id)
where PC.CategoryId in (
select child from mq
)
and P.PublishStatus = 1
order by P.PublishedDate DESC;
Any ideas how to get a nice LINQ query on this with pagination (current page, number of products per page, total product count)?
This is recursive / hiearchical query with table expression. EF does not provide support for such queries. If you want to receive data by single roundtrip to DB you must wrap it in stored procedure and import that procedure to your entity framework model.
Paging in SQL is also possible when using table expressions and ROW_NUMBER().
there is an idea. i haven't tested it, so dont blame if it doesn't work :P
var ids = context.TreeItems.Where(x => x.Id == parentId).Select(x => (int?)x.Id);
var tmp = ids;
while (true)
{
IQueryable<int?> localIds = tmp;
var subIds = context.TreeItems.Where(x => ids.Contains(x.ParentId)).Select(x => (int?)x.Id);
if (subIds.Any())
{
tmp = subIds;
ids = ids.Union(subIds);
}
else
break;
}
var allSubItems = context.TreeItems.Where(x => ids.Contains(x.Id));