I have a linq query which returns the ID of a question based on the questions text.
This ID is then needed to be used to relate a date in a date table to that particular question. The question is already stored and the date is stored at a different time.
The problem is that the query returns the questionID as an anonymous type and so when I need to assign that questionID as the questionID in another table, it throws an error, stating that the table is expecting a Guid. Following this, I converted the anonymous type to a string and then used the GUIDs convert feature to convert the string to a GUID, however it is now giving me the error that a GUID should be 32 characters and 4 dashes.
My thoughts regarding this are that the anonymous type is returning the questionID as “QuestionID = jkj939-89239829- etc etc.” – With the prefix of characters at the front, and thus when converting it to a GUID, the converted string contains these characters.
Have I missed something?
I really can’t understand why it would do this, and is there a way to remove the prefix returned by the anonymous type?
Help would be greatly appreciated.
Here is the code:
public static void GetQuesID(string quesText)
{
ExamineDataContext dc = new ExamineDataContext();
var matchedques = from q in dc.GetTable<Question>()
where q.QuestionText.Contains(quesText)
select new{
q.QuestionID
};
foreach (var element in matchedques)
{
MessageBox.Show(element.ToString());
}
try
{
Guid g = Guid.NewGuid();
Table<DateLastUsed> dlused = Repository.GetDateLastUsedTable();
DateLastUsed dlu = new DateLastUsed(); ;
string qidGuidString = matchedques.ToString();
Guid convQuesGuid = new Guid(qidGuidString);
dlu.DLUID = g;
dlu.QuestionID = convQuesGuid;
dlu.DateLastUsed1 = DateTime.Now;
dlused.InsertOnSubmit(dlu);
dlused.Context.SubmitChanges();
}
catch (Exception ex)
{
throw ex;
}
}
Unless I’m missing something, why don’t you just
select q.QuestionIDinstead of making a new anonymous-type wrapper?Alternatively, give the field a name (“
theID” below) and access it directly:Apparently, there was more to the question than I first thought. In response to the comment, keep in mind that you’re returning an enumeration of results in matchedques (hence the foreach above, right?). So the following line is also in error:
You either want
if matchedques should contain a single result, or a foreach loop if matchedques should contain multiple results.
Note that there’s no reason to convert a GUID to string and back again, and you can also use the query to return something more useful (namely, a new
DateLastUsedobject):