Help with EntityQuery working Silverlight C# - c#

I have the following code:
var data = (sender as Button).DataContext as Web.Booking;
EntityQuery<Web.Ticket> ticketQuery =
from t in _ticketContext.GetTicketsQuery()
where t.ticketId == data.ticketId
select t;
LoadOperation<Web.Ticket> loadTicket = this._ticketContext.Load(ticketQuery);
loadTicket.Completed += (s, args) => { MessageBox.Show("Loaded Tickets!"); };
ticketDomainDataSource.DataContext = loadTicket.AllEntities;
var ticketData = ticketDomainDataSource.DataContext as Web.Ticket;
string ticketName = ticketData.ticketName;
The main code that I'm having trouble with is the:
var ticketData = ticketDomainDataSource.DataContext as Web.Ticket;
string ticketName = ticketData.ticketName;
It returns an error:
Object reference not set to an
instance of an object.
Can anyone help me out on what I'm doing wrong here, I can't figure out what's null and how I can return proper data.
Thanks

Your issue is likely that DataContext cannot be cast to Web.Ticket. If you look at the documentation for C# -- as returns a null on a conversion failure. See - http://msdn.microsoft.com/en-us/library/cscsdfbt%28v=vs.71%29.aspx
If you change your line of code to
var ticketData = (Web.Ticket) ticketDomainDataSource.DataContext;
you should get a better cast error.

Related

Searching database with Linq

I am trying to search for data in my datagrid using the code sample below. I have had it working with the code looking a bit different, but I am now going to use async in my coding and I have tried to do so with the sample below, but have no idea how to change the code to work correctly.
private async Task btnSearchSysproStock_Click(object sender, RoutedEventArgs e)
{
using (DataEntities DE = new DataEntities())
{
List<SSData> stockSearch = await (from a in DE.tblSysproStocks where
(a => txtSearchSysproStock.Text == string.Empty || a.StockCode.Contains(txtSearchSysproStock.Text)) //The error is in this line
select new SSData
{
SID = a.StockID,
SCode = a.StockCode,
SDescription = a.StockDescription,
SConvFactAltUom = (float)a.ConvFactAltUom,
...
}).ToListAsync();
dgSysproStock.ItemsSource = stockSearch;
}
}
I am getting the following error:
Cannot convert lamba expression to type 'bool' because it is not a delegate type
Can anyone please help me to get this code that I am using to work. Thanks in advance! :)
LINQ where clause expects bool expression, you don't need lambda here :
from a in ...
where txtSearchSysproStock.Text == string.Empty ||
a.StockCode.Contains(txtSearchSysproStock.Text)
select ...

Should my query return null when it doesn't find any items?

I have a multiselectlist where a user can pick some or none inputvoltages. When the user selects no InputVoltages my query throws a null exception when I call .Tolist(). Why am I not just getting back an empty list?
I'm using MVC5 C# and entity framework 6.
repository
public IQueryable<InputVoltage> All
{
get { return context.InputVoltages; }
}
controller
var newInputVoltages = unitOfWorkPds.InputVoltageRepository
.All.Where(m => engineeringPdsEditViewModel.SelectedInputVoltages
.Contains(m.Id))
.ToList<InputVoltage>();
All does return a list but SelectedInputVoltages is null when nothing is selected. I was wondering if that was the issue.
When I use this query and add a where statement for my index page I don't receive a null error when I call ToList
IQueryable<EngineeringPdsIndexViewModel> query =
(from a in context.EngineeringPds
select new EngineeringPdsIndexViewModel
{
Id = a.Id,
Name = a.Name,
Status = a.Status,
AnnualQuantities = a.AnnualQuantities,
ToMarketDate = a.ToMarketDate,
SubmittedBy = a.SubmittedBy,
TargetPrice = a.TargetPrice
});
So I believe Brian has the right idea of what is wrong but here is the issue extended
I have a multiselect box that is populated in the get action method by
IList<InputVoltage> inputVoltagesList = unitOfWorkPds.InputVoltageRepository.All.ToList();
then
pdsEditViewModel.InputVoltageList = inputVoltagesList.Select(m => new SelectListItem { Text = m.Name, Value = m.Id.ToString() }); in my view I hav#Html.ListBoxFor(m => m.SelectedApprovals, Model.ApprovalList)
but when a user makes no selections the selectedInputvoltages comes into my post controller action as null how do I get it to come in as an empty list?
UPDATE
For anyone who runs into the same problem Brians first answer explains the issue. The work around for submitting a ListBox with empty lists can be found here
How can I return an empty list instead of a null list from a ListBoxFor selection box in Asp.net MVC?
Any Extension method defined in the BCL for IEnumerable<T> or IQueryable<T> that returns IEnumerable<T> or IQueryable<T> will not return null. It might return an empty collection, but that is very different to null.
try this:
var newInputVoltages = engineeringPdsEditViewModel.SelectedInputVoltages == null ?
unitOfWorkPds.InputVoltageRepository.All :
unitOfWorkPds.InputVoltageRepository.All.Where(m => engineeringPdsEditViewModel.SelectedInputVoltages.Contains(m.Id)).ToList();
Where will not return null. The problem is in the argument:
engineeringPdsEditViewModel.SelectedInputVoltages.Contains(m.Id)
A NULL engineeringPdsEditViewModel or SelectedInputVoltages can cause NullReferenceException to be thrown. So you need to do a null check against these objects.
You can see this play out with a similar test sample. Here we get a nullrefex because myString is null. So when Where executes it tries to do a comparison and blows up:
var test = new TestClass(1);
var test2 = new TestClass(2);
var test3 = new TestClass(3);
List<TestClass> tests = new List<TestClass>();
tests.Add(test);
tests.Add(test2);
tests.Add(test3);
string myString = null;
var result = tests.Where(t => myString.Contains(t.Myint.ToString())).ToList();
Console.WriteLine(result.Count);
Update: (To answer your comment)
You can return an empty list like this:
List<InputVoltage> newInputVoltages = new List<InputVoltage>();
if(engineeringPdsEditViewModel != null && engineeringPdsEditViewModel.SelectedInputVoltages != null)
{
//Where params are not null so its safe to use them
newInputVoltages = unitOfWorkPds.InputVoltageRepository
.All.Where(m => engineeringPdsEditViewModel.SelectedInputVoltages
.Contains(m.Id))
.ToList<InputVoltage>();
}
//else no need to do anything...just return the empty list created above
return newInputVoltages;
you will not get an empty list and it's expected behaviour it returns null.
just test the input (I used the Ternary Operator) when you create the variable and you won't need any validation later
var newInputVoltages = SelectedInputVoltages.Any()
? unitOfWorkPds.InputVoltageRepository
.All.Where(m => engineeringPdsEditViewModel.SelectedInputVoltages.Contains(m.Id))
.ToList<InputVoltage>()
: new List<InputVoltage>();

Getting errors with SqlParameter and ExecuteScalar

public TransImport()
{
ConnString = ConfigurationManager.ConnectionStrings["Connection"].ConnectionString;
conn_new = new SqlConnection(ConnString);
command_serial_new = conn_new.CreateCommand();
command_serial_new.CommandText = "SELECT 1 FROM YSL00 WHERE SERLNMBR = #slnr";
var p = new SqlParameter("#slnr", SqlDbType.NVarChar, 50);
command_serial_new.Parameters.Add(p);
//Here you will start reading flat file to get serialnumber.
//Here I have shown a simple call using one value 12345 but it will be 1000's of
//lines from flatfile.
if (CheckSerialNumber('12345'))
DisplayMessage("Good serialnumber"); //this function is not copied here.
}
private Boolean CheckSerialNumber(string SerialNumber)
{
command_serial_new.Parameters["#slnr"].Value = SerialNumber;
try
{
var itExists = (Int32)command_serial_new.ExecuteScalar() > 0;
if (itExists)
{
return true;
}
}
catch (Exception ex)
{
LogException(ex, "Error in CheckSerialNumber =>"+ command_serial_new.CommandText.ToString());
}
return false;
}
I get error in the above catch. It mentions
object reference not set to an instance of object
It is failing with the line that has ExecuteScalar.
I guess I am doing something wrong here, but unable to figure out so far.
Update 1: I have modified this question. Basically I created another question with an issue I am facing.. Also I have marked it as answered.
Here is the NEW question I have posted just now.
Getting timeout errors with SqlTransaction on same table
This happens if the ExecuteScalar() returns null. (eg, because no rows matched)
Since int is a value type, it cannot be null; therefore, you get an error.
Instead, you can cast it to int?, which is nullable.
#SLaks answer is correct.
Here is one more way to avoid the error. No need of null checking etc, Convert.ToInt32 takes care of everything.
var itExists = Convert.ToInt32(command_serial_new.ExecuteScalar()) > 0;
try:
int i;
object o = command_serial_new.ExecuteScalar();
if(o != null && Convert.ToInt32(o.ToString()) > 0)
{
//....
}
to verify that your query returned something

How to get the name of a dependency property

For binding purposes, we have a method that returns the most common dependency property for the framework element that was passed in. If we pass in TextBlock, this method returns TextBlock.TextProperty; RadMaskedTextBox returns RadMaskedTextBox.MaskedTextProperty, and so on.
While debugging, if type dp.Name, I get "Text", "MaskedText" respectively. But the dp.Name is not available in code.
I'm trying to do dynamic binding to a tooltip:
var binding = new Binding("Text") //Works
{
Source = frameworkElement
};
var binding = new Binding("MaskedText") //Works
{
Source = frameworkElement
};
var binding = new Binding(dp.Name) //Doesn't work
{
Source = frameworkElement
};
I can't figure out how to get "Text" or "MaskedText" from the dependency property, nor do I understand why it's hidden to begin with.
.Net Framework 4.5 / Silverlight 5
Thanks for any help or insight you can give!!
JD
Kevin, Thank you so much, you were pretty close. It's a non-public field, so I did this:
{
var dpType = dp.GetType();
var nameField = dpType
.GetFields(BindingFlags.NonPublic | BindingFlags.Instance)
.Single(pi => pi.Name == "Name");
var name = nameField.GetValue(dp);
}
However, I get an FieldAccessViolation when I call nameField.GetValue(dp). I can see it in the watch, but can't actually get to it. I wish someone would explain this, because I don't understand why I should not be able to get/use this value. Especially when that (the string "MaskedText") is what has to supplied for the path. UGH!!!
But thank you very much for your help!
JD
I'm not 100% sure what is going on without further clarification... But making some assumptions it should be possible to get the name via reflection...
var typeOfDp = dp.GetType();
var nameProperty = typeOfDp
.GetFields(BindingFlags.NonPublic | BindingFlags.Instance)
.Single(t => t.Name == "Name");
var name = nameProperty.GetValue(dp);
var binding = new Binding(name) //Maybe it will work?
{
Source = frameworkElement
};

how to convert int to string in Linq to entities

My Db column in a string (varchar) and i need to assign it to a int value.
I am using linq to query.Though the code compiles am getting an error at the run time .
Thanks in advance.
PFB my query :
var vlauesCap = from plan in entities.PA_RTM_CAP_Group
select new Business.PartnerProfile.LookUp
{
Id =Convert.ToInt32(plan.cap_group_code),
//(Int32)plan.cap_group_code,
Value = plan.cap_group_name
};
return vlauesCap.ToList();
The EF provider does not know how to translate Convert.ToInt() into SQL it can run against the database. Instead of doing the conversion on the server, you can pull the results back and do the conversion using linq to objects:
// the ToList() here causes the query to be executed on the server and
// the results are returned in a list of anonymous objects
var results = (from plan in entities.PA_RTM_CAP_Group
select new
{
Code = plan.cap_group_code,
Name = plan.cap_group_name
}).ToList();
// the conversion can now be done here using Linq to Objects
var vlauesCap = from r in results
select new Business.PartnerProfile.LookUp
{
Id = Convert.ToInt32(r.Code),
Value = r.Name
};
return vlauesCap.ToList();
You can't do this directly, what you can do is declare a private variable to handle your "mapped" value, and expose the unmapped property...
[Column(Name = "cap_group_code", Storage = "m_cap_group_code")]
private string m_cap_group_code;
public int cap_group_code {
get
{
return Int32.Parse(m_cap_group_code);
}
set
{
m_cap_group_code = value.ToString();
}
}
Try this:
var vlauesCap = from plan in entities.PA_RTM_CAP_Group
select new Business.PartnerProfile.LookUp
{
Id =Convert.ToInt32(plan.cap_group_code),
Convert.ToInt32(plan.cap_group_code),
Value = plan.cap_group_name
};
return vlauesCap.ToList();
Why aren't you using casting for such a purpose, which is a more effective way of achieving this.
Just replace Convert.ToInt32(plan.cap_group_code) with (int)plan.cap_group_code
Do remember, there should be a value in the string and is int, else it will show Exception. If you are not sure about it, then you can further expand the casting to use null coalesciting operator

Categories