selecting a column values from a Table using LINQ (Entity Framework) - sql

Im trying to display a dropdown with values from table 'Events'. I have created a Model.edmx which has the structure of the database. Now i have to just write LINQ code to display one column values. I am kind of new to LINQ.
Dim Events=" LINQ select statement part???"
ddlEvent.DataSource = Events
ddlEvent.DataBind()
ddlEvent.Items.Insert(0, New ListItem("-Type-", ""))

DropDownLists work with 2 fields:
the DataTextField represents the field holding the text of the options that will be displayed to the user
the DataValueField represents the field hoding the value associated with each option
So in your case, you could get it to work with something like:
Dim events As List(Of Event) = yourDbContext.Events.ToList()
ddlEvent.DataSource = events
ddlEvent.DataTextField = "NameOfThePropertyYouWantDisplayed"
ddlEvent.DataValueField = "NameOfThePropertyYouWantAsValue"
ddlEvent.DataBind()
Note, however, that the query will retrieve every property from the database. This can hurt performance if your Event class has a lot of properties.
To avoid this, you could use the LINQ Select operator, used for projection. This could be used to retrieve only the necesseray data from the database. You can have a look on the MSDN here

Context.Events.ToList();
Where, Context is your EF db context. Update your filter condition in where clause

ddlEvent.DataSource = from x in Context.Events select x.column;
here 'x' is a variable and 'column' in 'x.column' is required column you want to fetch.
Where, Context is your EF db context.

Related

VB.net Datatable dynamic columns Query fields with LINQ

For a project i'm trying to make a dynamic query to a datatable field.
Let me explain what i'm doing.
Step 1. Read database file with OLEDB and create snapshot to datatable.
Step 2. Create dynamically checkboxes that represents the field names from the datatable.
Step 3. User can create query by selecting the checkboxes. Thus filtering the result.
The problem that i'm having is that i don't know upfront how many and what name's the Fields/Column are getting in the datatable. It is no problem making the query if i fill in the Field names hardcoded:
MyDataview = (From p In MyDataTable _
Where p.Field(Of Boolean)("customer") = True And _
p.Field(Of Boolean)("customer_ID") = True
Select p).AsDataView
However this would be a problem in the future as the database therefore datatable could change and expand or shrink.
So in SQL syntax this wouldn't be any problem. Simple append the field name that correspondent with the checkbox to a Where clause and where good to go.
This is exactly what i'm trying to achieve. I have searched for many hours and tried allot with system.linq.dynamic but i can't get it to work. example:
Dim valueQuery = MyDataTable.AsEnumerable.Where("customer").[Select]("customer")
causes exception:
No property or field 'customer' exists in type 'DataRow'
Or
Dim valueQuery = MyDataTable.AsEnumerable.Where("Field=customer").[Select]("customer")
causes exception:
No property or field 'customer' exists in type 'DataRow'

Filtring/Searching from a DataGridView

I have a DataGridView in a form which displays a client list with the columns ID, First Name, Last Name, Address. I also included a TextBox to perform the search query. I want to filter my DataGridView based from the given columns using a single TextBox (like a multi data filter/search where I can select from those four columns by typing on a single TextBox).
The question is: am I required to create a binding source for here (I populate my DataGridView using sql database) or is there a way to create filters without having to add a binding source?
You don't populate your grid using a sql database. You populate your grid from a SQL Server database suing something else in between, e.g. a SqlDataAdapter and a DataTable.
A BindingSource is supposed to be a one-stop shop for working with bound data so, while you don't have to use one, I would recommend doing so. Whether it can help you filter your data depends on what it's bound to. The BindingSource doesn't actually do the work of filtering itself but rather passes the work on to the underlying IBindingListView implementation if there is one. For instance, if the underlying data source is a DataTable then the RowFilter of its DefaultView will be used. You could set the DefaultView.RowFilter yourself.
If you want to do all the heavy lifting yourself then you could also search the grid yourself and then hide the rows that don't match. Those rows would still exist though, so you'd have to take that into account when using the data in code.
You have to create a query to retrive a data using like keyword by passing parameter value in form
Example:
pass the parameter from
form(cmd.parameters.add(nvarchar, 20).value = "textbox.text")
create a stored procedure
CREATE PROCEDURE procedure_name
#searchvalue varchar(20)
AS
BEGIN
SELECT
ID, FirstName, LastName, Address
FROM
tablename
WHERE
FirstName LIKE '%#SearchTerm%'
END
This above stored procedure will retrieve all the rows where the FirstName column value corresponds to that name
Then pass the result to gridview

Using LINQ to determine if a value exists in a DB table

I have a SQL table which has a simple string field that may contain a single value (like 'ABC' for example) or it may contain a list delimited by the pipe ('|') character (like 'ABC|EDF|GHI' for example).
If I have a SharePoint list and want to cross check to make sure that all of the values in my SP list exist in the SQL table, I can easily do it assuming the SQL field only has a single value:
var listitems = from SPListItem item in spList.Items
where item[myfieldname].Equals(valueImChecking)
select item;
How do I use a similar approach to check the same SQL field assuming it contains list of value delimited by '|'? If this field's value is 'ABC|EDF|GHI' and I'm checking if it contains 'GHI' for example, how do I build the query in LINQ?
TIA,
-Tony.
var listitems = from SPListItem item in spList.Items
where item[myfieldname].ToString().Contains(valueImChecking)
select item;
Contains method on string should help.
I would suggest to split the values and write them to a separate table. I don't think it's a good design to store multiple values in the same field if you want to lookup them later.
If you don't want to change your database you can use shahkalpesh's answer. If however some values may contain other values (like WXYZ contains XYZ) this will only give you a list of possible candidates. You need to check the result in-memory:
// this filters for possible candidates
var candidates = from item in spList.Items
where item[myfieldname].ToString().Contains(valueImChecking)
select item;
// this filters the result using ling-to-objects
var listItems = from candidate in candidates.AsEnumerable()
where candidate[myfieldname].ToString().Split('|').Contains(valueImChecking)
select candidate;
Using AsEnumerable switches to Linq-To-Objects. This is required because LINQ to SQL does not support Split.
You can do some pre-filtering using the first query (which was taken from shahkalpesh's answer).
If your Items table is small it might also be a good idea to load everything into memory and do the check with ling-to-objects (using only the second query).

Entity Framework Custom SQL Query returning generic type

I'm trying to make a generic reporting system so that I can add reports to my program on the fly, rather than issuing a new version of the program every time I have to add in a report.
Currently, I have it partly working;
My custom report SQL is stored in a table, along with the report name. The report name is used for the buttons for the user to click, when they click the button, I want the SQL to execute and be bound to a gridview, so it's as generic as possible.
This seems to be where the troubles come though. Getting the SQL and executing it is fine, but binding it to a gridview seems impossible, I only get one column, called Column, that displays 1 row with a value of System.Object.
I think the problem is because I'm returning data from multiple tables, i.e.
SELECT c.CertificateName, e.EntityName,
ce.CertificateDate, ce.CertificateExpiry, ce.CertificateNumber
FROM FCERTSTest.dbo.CertificateEntries ce
INNER JOIN FCERTSTest.dbo.Certificates c
ON c.CertificateID = ce.Certificate_ID
INNER JOIN FCERTSTest.dbo.Entities e
ON e.EntityID = ce.Entity_ID
WHERE FirstNotificationSent = '1'
I'm currently using
using (DBContainer db = new DBContainer())
{
grid.DataSource = db.Database.SqlQuery<dynamic>(SQLCommand).ToList();
}
I've tried replacing dynamic with object and get the same problem...
I understand that the best solution would be to have a custom class and replace dynamic with that custom class, but then I lose the benefits of it being generic as a different report may not return the same results and I would need a new custom class...
Use SqlDataAdapter and DataSet. EF doesn't work with "dynamic queries" where you don't have special type for result set.

Update specific rows in LINQ to SQL result set

I have a page with a form on it and needs a range of dates. Thus I've placed a number of textboxes on the page into which users can type dates. When the user clicks the save button I want to trigger a LINQ update to the SQL Server...all the rows already exist, so I'm just updating existing data. How can I do this?
For example, lets say my table looks like this:
Column Names: Description dateValue
Column Values:
Birthdate 1/1/1990
Anniversary 1/10/1992
Death 1/1/1993
I want to do something like this:
hupdate.Description("Birthdate").dateValue = TextBox1.Text
hupdate.Description("Anniversary").dateValue = TextBox2.Text
hupdate.Description("Death").dateValue = TextBox3.Text
hconfig.SubmitChanges()
Is there a way to do this with LINQ?
I don't think there is a way to do that with only LINQ. However, there are other ways to achieve that like:
if you use Entity Framework you can use LINQ to query the data, then change the entities (within your c# code) and update the DB via them.
Create a stored procedure that updates the data, according to your description this stored procedure doesn't seem like a complicated one.