I'm wondering why is it returning a null value in the code that i made below:
using (var context = new MusicStoreDBEntities())
{
var bay = (from g in context.stringInstrumentItems
where g.brand.name == name.Text select g)
.FirstOrDefault();
context.stringInstrumentItems.Remove(bay);
context.SaveChanges();
}
The var bay is returning null. What have i done wrong? Here is the equivalent raw sql query that I'm trying to turn into an entity framework:
string queryGuitarItems = "DELETE S FROM stringInstrumentItem S JOIN brand B ON S.brandId = B.brandId WHERE B.name = @brand";
using (SqlConnection connectionGuitarItems = new SqlConnection(ConfigurationManager.ConnectionStrings["musicStoreConnection"].ToString()))
{
using (SqlCommand commandGuitarItems = new SqlCommand(queryGuitarItems, connectionGuitarItems))
{
connectionGuitarItems.Open();
commandGuitarItems.Connection = connectionGuitarItems;
commandGuitarItems.Parameters.Add(new SqlParameter("@brand", name.Text));
commandGuitarItems.ExecuteNonQuery();
connectionGuitarItems.Close();
commandGuitarItems.Parameters.Clear();
}
}
Let me know if the two queries are similar or not. I'm really trying to change all my raw sql queries into entity framework and this is a start.
FirstOrDefault()returns null if nothing is found matching your conditions, are you sure that you have a matching item in your database?FirstOrDefault()may returnnullwhen no matching item is found. So check for that null.