Why does this LINQ query assign a value of 1 to a NULL value from the database? - sql

The ExamVersion class has an int? property named SourceSafeVersionNum
When I execute the following code:
var query = from examVersion in db.ExamVersions
where examVersion.ExamVersionID == ExamVersionID
select examVersion;
foreach (ExamVersion examVer in query.ToList())
{
yield return examVer;
}
examVer.SourceSafeVersionNum is set to 1 even though it is NULL in the database.
When I run the SQL code generated by LINQ in SQL Server, the SourceSafeVersionNum column value is NULL (as I'd expect) but in the foreach loop the examVer.SourceSafeVersionNum is 1.
I can't find anywhere in the code where a default value is assigned or any similar logic.
Any ideas why/where this value is being set to 1?
Here is the property declaration (generated by a .dbml file)
[Column(Storage="_SourceSafeVersionNum", DbType="Int", UpdateCheck=UpdateCheck.Never)]
public System.Nullable<int> SourceSafeVersionNum
{
get
{
return this._SourceSafeVersionNum;
}
set
{
if ((this._SourceSafeVersionNum != value))
{
this.OnSourceSafeVersionNumChanging(value);
this.SendPropertyChanging();
this._SourceSafeVersionNum = value;
this.SendPropertyChanged("SourceSafeVersionNum");
this.OnSourceSafeVersionNumChanged();
}
}
}

Have you tried setting a breakpoint in the set{} method of the property to see what else might be populating its value? You might catch the culprit in the act, then look at the Call Stack to see who it is.

As a follow up to this, here is what happened:
The code that retrieved the value from the database was being called twice but through two different code paths. The code path that was assigning the value of 1 was being stepped over by the debugger so I didn't see it.

Related

How to get specific data from database in android studio?

The only data that should appear when I click the "view data button" should be the employee's personal data by searching its employee id.
This is my code:
public void viewAll() {
btnview.setOnClickListener(
new View.OnClickListener() {
#Override`enter code here`
public void onClick(View v) {
Cursor res = EmployeeData.getAllData();
if(res.getCount() == 0) {
// show message
showMessage("Error","Nothing found");
return;}
How can I get the specific data from the existing database?
You need to replace the getAllData with a method that SELECTs the appropriate data using a WHERE clause which is invoked with the employeeId being passed to it (after extracting the employeeId from the clicked item ).
You then need to process the Cursor by extracting the data from it, if any exists.
So you could have something like the following in your class that extends SQLiteOpenHelper :-
public Cursor getEmployeeDataById(long id) {
return this.getWritableDatabase().query("the_table",null,"employeeId=?",new String[]{String.valueOf(id)},null, null,null);
}
obviously "the_table" and "employeeId" should be replaced by the actual names.
see Query for an explanation of the method's parameters.
the Query (method which has 4 signatures) is a convenience method that returns a Cursor object.
-It generates the SQL on your behalf e.g. the above would generate the SQL SELECT * FROM the_table WHERE employeeId=?
- where the ? is bound (prevents SQL Injection) to the passed id value by SQLite.
When extracting the data from the Cursor, rather than checking the count, you can rely upon the fact that the Cursor's will return false if it cannot move to the first row (i.e. there is no first row). So extracting the data could be along the lines of:-
Cursor csr = EmployeeData.getEmployeeDataById(extracted_employee_id);
if (csr.moveToFirst()) {
.... extract the data from the cursor
} else {
showMessage("Error","Nothing found");
}

Returning distinct data for a dropdownlist box with selectlistItem

I have a field in my database with duplicates. I want to use it in a dropdown list, which has to return distinct data.
Here is the method that I created to do this:
public IEnumerable<SelectListItem> GetBranches(string username)
{
using (var objData = new BranchEntities())
{
IEnumerable<SelectListItem> objdataresult = objData.ABC_USER.Select(c => new SelectListItem
{
Value = c.BRANCH_CODE.ToString(),
Text = c.BRANCH_CODE
}).Distinct(new Reuseablecomp.SelectListItemComparer());
return objdataresult;
}
}
Here is the class I am using:
public static class Reuseablecomp
{
public class SelectListItemComparer : IEqualityComparer<SelectListItem>
{
public bool Equals(SelectListItem x, SelectListItem y)
{
return x.Text == y.Text && x.Value == y.Value;
}
public int GetHashCode(SelectListItem item)
{
int hashText = item.Text == null ? 0 : item.Text.GetHashCode();
int hashValue = item.Value == null ? 0 : item.Value.GetHashCode();
return hashText ^ hashValue;
}
}
}
Nothing is returned and I get the error below. When I try a basic query without Distinct, everything works fine.
{"The operation cannot be completed because the DbContext has been disposed."}
System.Exception {System.InvalidOperationException}
Inner exception = null
How can I return distinct data for my dropdown?
Technically, your problem can be solved simply by appending .ToList() after your Distinct(...) call. The problem is that queries are evaluated JIT (just in time). In other words, until the actual data the query represents is needed, the query is not actually sent to the database. Calling ToList is one such thing that requires the actual data, and therefore will cause the query to be evaluated immediately.
However, the root cause of your problem is that you are doing this within a using statement. When the method exits, the query has not yet been evaluated, but you have now disposed of your context. Therefore, when it comes time to actually evaluate that query, there's no context to do it with and you get that exception. You should really never use a database context in conjuction with using. It's just a recipe for disaster. Your context should ideally be request-scoped and you should use dependency injection to feed it to whatever objects or methods need it.
Also, for what it's worth, you can simply move your Distinct call to before your Select and you won't need a custom IEqualityComparer any more. For example:
var objdataresult = objData.ABC_USER.Distinct().Select(c => new SelectListItem
{
Value = c.BRANCH_CODE.ToString(),
Text = c.BRANCH_CODE
});
Order of ops does matter here. Calling Distinct first includes it as part of the query to the database, but calling it after, as you're doing, runs it on the in-memory collection, once evaluated. The latter requires, then, custom logic to determine what constitutes distinct items in an IEnumerable<SelectListItem>, which is obviously not necessary for the database query version.

Access object members from Instance ID

I'm getting the Instance ID of an object from collision_line()
Now that I have this instance, I want to get it's image_angle, but I get an 'unknown variable' message when I try that.
What should I do?
what is the value of this collision_line()? The collision_line() function returns an instance id - however when nothing is found it returns noone (-4).. So you'll have to test for that first:
var inst, imgangle;
inst = collision_line(...);
if (inst != noone) {
imgangle = inst.image_angle;
//etc etc
}
or alternativelly (more cleanly in GM), we can "abuse" the with statement. With executes all following code from the perspective of the given instance id (or for all instances of a certain object when given the object id).
However the value noone will automatically prevent any execution.
var inst, imgangle;
inst = collision_line(...);
with (inst) {
imgangle = image_angle;
//note that we do no longer have to put "inst." before getting a variable
//etc etc
}

New ArrayList filtering from another ArrayList using a String as Filter

In my program, a Die (dice for embroidery) is a class with different fields. One of them is of the type String and it is called haveIt. So, if the user of the program enters the word "Yes" on the haveIt field, he should be able to track a list of all the Dies he has, on the myInventory list.
How do I do this? Should I create the myInventory ArrayList<Die> on the fields and constructor of my Contoller class or should I built it inside a special method in that class?
I have tryed everything and nothing works. But I am really new on this.
Here is my last attempt, creating a loop to create the new ArrayList<Die> (that has "Yes" on the haveIt field) from a special getMyInventory method in my Controller class:
public ArrayList<Die> getMyInventory(Die anyDie) {
for (int counting = 0; counting <
diesBigList.Count ; counting++);
{
if
(((Die)diesBigList[counting]).doIHaveIt.contains("Yes"))
myInventory.add(diesBigList[counting]);
return myInventory;
}
}
It does not compile. It tells me that the result should be an Array type but it is resolved as ArrayList... (and I do not comprendo that).
Thanks in advance.
Your missing a return statement. What if this is never true?
if (((Die)diesBigList[counting]).doIHaveIt.contains("Yes"))
you never reach your return statement
Here is the answer
public ArrayList<Die> getMyInventory(Die anyDie) {
ArrayList<Die> myInventory = new ArrayList<Die>();
for (int counting = 0; counting < diesBigList.Count; counting++) {
if (((Die)diesBigList[counting]).doIHaveIt.contains("Yes")) {
myInventory.add(diesBigList[counting]);
}
}
return myInventory;
}
Also there could be a problem with this: diesBigList.Count I have no idea where you got that object or what it's methods looks like but I presume in my code your making that call correctly.

How to work around NHibernate caching?

I'm new to NHibernate and was assigned to a task where I have to change a value of an entity property and then compare if this new value (cached) is different from the actual value stored on the DB. However, every attempt to retrieve this value from the DB resulted in the cached value. As I said, I'm new to NHibernate, maybe this is something easy to do and obviously could be done with plain ADO.NET, but the client demands that we use NHibernate for every access to the DB. In order to make things clearer, those were my "successful" attempts (ie, no errors):
1
DetachedCriteria criteria = DetachedCriteria.For<User>()
.SetProjection(Projections.Distinct(Projections.Property(UserField.JobLoad)))
.Add(Expression.Eq(UserField.Id, userid));
return GetByDetachedCriteria(criteria)[0].Id; //this is the value I want
2
var JobLoadId = DetachedCriteria.For<User>()
.SetProjection(Projections.Distinct(Projections.Property(UserField.JobLoad)))
.Add(Expression.Eq(UserField.Id, userid));
ICriteria criteria = JobLoadId.GetExecutableCriteria(NHibernateSession);
var ids = criteria.List();
return ((JobLoad)ids[0]).Id;
Hope I made myself clear, sometimes is hard to explain a problem when even you don't quite understand the underlying framework.
Edit: Of course, this is a method body.
Edit 2: I found out that it doesn't work properly for the method call is inside a transaction context. If I remove the transaction, it works fine, but I need it to be in this context.
I do that opening a new stateless session for geting the actual object in the database:
User databaseuser;
using (IStatelessSession session = SessionFactory.OpenStatelessSession())
{
databaseuser = db.get<User>("id");
}
//do your checks
Within a session, NHibernate will return the same object from its Level-1 Cache (aka Identity Map). If you need to see the current value in the database, you can open a new session and load the object in that session.
I would do it like this:
public class MyObject : Entity
{
private readonly string myField;
public string MyProperty
{
get { return myField; }
set
{
if (value != myField)
{
myField = value;
DoWhateverYouNeedToDoWhenItIsChanged();
}
}
}
}
googles nhforge
http://nhibernate.info/doc/howto/various/finding-dirty-properties-in-nhibernate.html
This may be able to help you.