Linq “outer join” on a non-nullable integer column

Today I ran into a problem when running the following Linq query with an “outer join”.

from au in dcApp.aspnet_Users
where au.UserId == new Guid("X")
select new
{
   au.UserName,
   au.ApplicantInfo.FirstName,
   au.ApplicantInfo.LastName,
   au.ApplicantInfo.CurrentStep
};

The problem is that the Current Step is a not null column in the database; so it is of type int not int? . But in this query, I’m using Linq to get the ApplicantInfo row associated with the aspnet_Users row. The ApplicantInfo row might or might not exist. When the row does not exist linq is trying to convert that null into an int type so you get the following error:

“The null value cannot be assigned to a member with type System.Int32 which is a non-nullable value type.”

What is really interesting is that it is only throwing that error with the CurrentStep column in the ApplicantInfo table, not with the FirstName or LastName cols that are also not null in the db. This probably has to do with the fact that the string type is a reference type (and the int type is a value type) and C# treats strings in unique ways.

This is the work-around I came up with:

from au in dcApp.aspnet_Users
where au.UserId == new Guid("X")
select new
{
   au.UserName,
   au.ApplicantInfo.FirstName,
   au.ApplicantInfo.LastName,
   CurrentStep = au.ApplicantInfo == null ? "" : au.ApplicantInfo.CurrentStep.ToString()
};
Advertisements

Getting an ASP.NET CheckBoxList to work with a RequiredFieldValidator

I ran into a situation where I needed the System.Web.UI.WebControls.CheckBoxList to work with a System.Web.UI.WebControls.RequiredFieldValidator.

I found a clever and really easy way to fix it. I subclassed the CheckBoxList class to add the ValidationProperty that the RequiredFieldValidator is looking for.

Just declare this class:

[ValidationPropertyAttribute("ValidateableProperty")]
public class ValidateableCheckBoxList : CheckBoxList
{
    
    public string ValidateableProperty
    {
        get { return (this.Items.Cast<ListItem>()
            .Where(i => i.Selected).Count() > 0) ? 
            "something was selected" : ""; }
    }
}

And instead of using a CheckBoxList in your code, use a ValidateableCheckBoxList.

On the aspx file you can now work with the ValidateableCheckBoxList just like you would with a plain TextBox. I’m not a JavaScript guru so I did not implement or even thought about how to implement the client side validation.

        <ans:ValidateableCheckBoxList runat="server" 
            ID="testCheckBoxList">
            <asp:ListItem Text="asdf" />
            <asp:ListItem Text="asdf" />
            <asp:ListItem Text="asdf" />
        </ans:ValidateableCheckBoxList>
        <asp:RequiredFieldValidator runat="server" ID="rfvTest" 
            ControlToValidate="testCheckBoxList" Text="Failed validation"  />