Julio Motol Julio Motol - 4 days ago 5
C# Question

Multiple where conditions with Entity Framework on a WPF application

How to select a single item with multiple where conditions?

my code looks like this:

private void submitEntry(object sender, RoutedEventArgs e) {
using ( var ctx = new Service()) {
try {
//gets the content of the combobox
string selection1 = comboBox1.SelectedItem.ToString();
//splits the value of the previously obtained content
String[] cond1 = selection1.Split(' ');
//this where things get smuggled up.
var query1 = from p in ctx.products where p.brand == cond1[ 0 ] &&
p.model == cond1[ 1 ]
select p.prodId;
//for testing purposes
MessageBox.Show(query1.ToString());
}catch {
MessageBox.Show("ERROR 404: Database Not Found");
}
}
}


I'm using Entity Framework, SQL Server Compact 4.0, Visual Studio.
it keeps on showing the ERROR 404. I've already checked some of the question related to my problem but none of them seems to work for me.

Answer

You can't use an indexer in a Linq to Entities query. If you always going to have as result of split two strings then you can build your conditions this way:

String[] cond1 = selection1.Split(' ');
var val1=cond1[0];
var val2=cond1[1];

 // You need to call FirstOrDefault to select just one element
 var productId=(from p in ctx.products 
                where p.brand == val1 &&       
                      p.model == val2 
               select p.prodId).FirstOrDefault();

 MessageBox.Show(productId!=null?productId.ToString():"");
Comments