Entity Framework 6 + C# passing a combobox.SelectedValue as a parameter for context.CreateQuery something simple i am missing?

后端 未结 2 854
花落未央
花落未央 2021-01-26 23:38
ObjectContext context = ((IObjectContextAdapter)db).ObjectContext; 
string queryString = @\"SELECT VALUE c FROM Product AS c WHERE c.ProductType = \" + comboBox1.Selecte         


        
相关标签:
2条回答
  • 2021-01-27 00:14

    You have to add a parameter to your query, that is:

    var context = ((IObjectContextAdapter)db).ObjectContext;
    
    var queryString = @"SELECT VALUE c FROM Product AS c WHERE c.ProductType = @productType";
    
    var productQuery = context.CreateQuery<Product>(queryString, new ObjectParameter("productType", comboBox1.SelectedValue);
    
    0 讨论(0)
  • 2021-01-27 00:28

    I will tell you the reason in a bit. Let's go through this code first so I can explain what the issue could be.

    Here is a Person class:

    public class Person 
    {
       public int Age { get; set; }
       public string Name { get; set; }
    }
    

    Here is a list we will bind the combobox to:

    var persons = new List<Person>() { new Person { Age = 35, Name = "George" } };
    

    Here are different ways to set the binding:

    comboBox1.DataSource = persons;
    
    comboBox1.DisplayMember = "Name";
    comboBox1.ValueMember = "Name";
    

    combobox1.SelectedValue will return "George".

    Here is another way to set the binding:

    comboBox1.DataSource = persons;
    
    comboBox1.DisplayMember = "Name";
    

    combobox1.SelectedValue will return a Person object.

    Your issue is most likely because SelectedValue is not returning what you expect it to return.

    0 讨论(0)
提交回复
热议问题