How should I write this in LINQ? - c#

I have three tables I'm getting info from: User, Field, FieldUserInput. I already know the userId which is what I use to find out what fields the user has input. Then I want to get the value of those fields that the user has input in FieldUserInput.
I first wrote this query in plain old sql but I want to use LINQ as much as possible since that's why I use Entity Framework.
SELECT fielduserinput.field_idField, fielduserinput.userInput, fielduserinput.time
FROM fielduserinput
WHERE fielduserinput.userId = #userId
Any suggestions as to how I would write this in LINQ?

Considering you have a datasource filled with data.
var matchingRows = from rows in fielduserinput.AsEnumarable()
where string.compare(rows["userId"].ToString(),userID)==0
select rows;

var result = from row in fielduserinput
where row.userId = "???"
select new { row.field_idField, row.userInput, ...};

var response = fielduserinput
.Where(x=>x.userid == #userid)
.Select(x=>new { field_idfieldid = x.field_idfieldid, etc })
.ToList()

Related

How to convert linq query into a datatable

I know there are quite a few post on this subject but none of them seem to work for me.
I am trying to convert a linq query into an object that is acceptable for my telerik gridview.
What I have:
var allProjectItems = from x in db.DateItems.AsEnumerable()
where
x.Date.ProjectId == projectId
select new
{
ItemDate = (DateTime?)x.Date.ItemDate,
LastName =
((from Users in db.Users
where
Users.UserId == x.Date.AddedByUserId
select new
{
Users.Lastname
}).FirstOrDefault().Lastname),
DateItemId = x.DateItemId,
DateItem1 = x.DateItem1,
DateValue = x.DateValue,
DateId = x.DateId,
DateType = x.DateType
};
I've tried adding .AsEnumerable() onto each table in query but I still am not able to use the query for the gridview or to convert into a datatable with CopyToDataTable method.
Ive also tried to specify requested attributes like x.Field("ProjectId") but Field is not an option.
Can anyone help?
Thanks
Selecting off an anonymous type is going to frustrate you down the road when you actually want to know what object is selected in your gridview.
Just select your DataItem and bind it to your gridview, and set up your Binding on the gridview to show columns for the properties you want to display in the gridview.
//Obviously this is simplified and doesn't include your users stuff, but I think you get the idea.
var allProjectItems = (from x in db.DateItems
where
x.Date.ProjectId == projectId
select x).ToList();
You will have to set up your bindings on your gridview to show the data you want. As for the user business, I'd set up a partial class on the DataItem that will use navigational properties to get the user and return the values you want.

wpf and ef select part of a table with include

I have a table with many fields and I want to get only a few individual fields, I work with EF and I add another table to the query as follows
var Test= ve.Folders.Include("Hosting")
.Where(a => a.Collateral!= true)
.AsEnumerable()
.Select(p => new
{
id = p.Folder_Id,
name = p.Full_Name,
add = p.Address,
date1 = p.Collateral_Date,
sName = p.Hosting._Name
})
.ToArray();
But with the field (sName= p.Hosting._Name) that is associated with the second table without any value query not working
Many attempts have been tried but without result (interesting when I ask without Select everything works well)
Thanks in advance for any help
One thing to note is that, in this case, there's little benefit to the Select after the call to AsEnumerable, since all the data in the table is still queried from the database (not just the fields you specifiy).
If you want to avoid that, and only query those five fields, you can remove the AsEnumerable call. That means the Select will execute as part of the SQL query. This also means the Include is unnecessary, since the Select will query all of the data you want.
var Test= ve.Folders
.Where(a => a.Collateral!= true)
.Select(p => new
{
id = p.Folder_Id,
name = p.Full_Name,
add = p.Address,
date1 = p.Collateral_Date,
sName = p.Hosting._Name
})
.ToArray();

Building a custom|progressive query in LINQ?

I have a page with five text boxes, each one representing a field in my database table and a search button:
If I were using SQL I could build my SQL statement depending on which fields have data in them.
However, I want to use LINQ, and I'm at a loss as to how to accomplish this. For instance, take a look at the query below:
var db = new BookDBDataContext();
var q =
from a in db.Books
where a.Title.Contains(txtBookTitle) &&
a.Author.Contains(txtAuthor) &&
a.Publisher.Contains(txtPublisher)
select a.ID;
The query above will return data where all the fields match data in the table. But, what if the user didn't enter an Author in the txtAuthor field? If I were building this as a query string, I could check each field for data and add it to the query string. Since this is LINQ, I can't dynamically change the search criteria, it seems.
Any advice would be greatly appreciated!
var db = new BookDBDataContext();
var q = (from a in db.Books
where a.Title.Contains(txtBookTitle));
if(!String.IsNullOrEmpty(txtAuthor))
{
q = q.Where(a => a.Author.Contains(txtAuthor));
}
if(!String.IsNullOrEmpty(txtAuthor))
{
q = q.Where(a => a.Publisher.Contains(txtPublisher));
}
var id = q.Select(a => a.ID);
from a in db.Books
where (string.isNullorWhiteSpace(search) || a.Title.Contains(search)) &&
(string.isNullorWhiteSpace(txtAuthor) || a.Author.Contains(txtAuthor) ) &&
(string.isNullorWhiteSpace(txtPublisher) || a.Publisher.Contains(txtPublisher))
select a.ID;

LINQ statement that returns rownumber of element with id == something?

How to write LINQ statement that returns ROWNUMBER of element with id == something?
There is no direct way to do this that I'm aware of. You'd have to pull the whole query down to the client, and the from there you could project in the row numbers. As an alternative, you could write a stored procedure that uses ROW_NUMBER, and then hit that proc from Linq to SQL.
In your case, the only way you're going to be able to do this would be client side. Keep in mind that the following statement is NOT going to do this at the server, but will pull down your whole table and get the index at the client...
using (var dc = new DataClasses1DataContext())
{
var result = dc.Users
.AsEnumerable() // select all users from the database and bring them back to the client
.Select((user, index) => new // project in the index
{
user.Username,
index
})
.Where(user => user.Username == "sivey"); // filter for your specific record
foreach (var item in result)
{
Console.WriteLine(string.Format("{0}:{1}", item.index, item.Username));
}
}
You should be able to use the Skip and Take extension methods to accomplish this.
For example, if you want row 10:
from c in customers
where c.Region == "somewhere"
orderby c.CustomerName
select new {c.CustomerID, c.CustomerName}
.Skip(9).Take(1);
How To Project a Line Number Into Linq Query Results
How To Project a Line Number Into Linq Query Results

Best method for programmatically requesting db table columns using LINQ

Is there a good way of requesting only specified columns from the database using LINQ? I want to be able to select only certain columns depending on arbitrary conditions from code.
You can create anonymous types for each condition, which contain only the columns you specify.
var anonymousType = from item in itemCollection
select new {Column1 = item.Column1, Column2 = item.Column2};
var anonymousType2 = from item in itemCollection
select new {Column2 = item.Column2, Column3 = item.Column3};
Not sure exactly what you mean.
Are you maybe wanting to pull different columns based on a conditional?
Something like this?
if(condition)
{
table.Select(x => x.ColumnA);
}
else
{
table.Select(x => x.ColumnB);
}

Categories

Resources