Dylan Czenski
Dylan Czenski

Reputation: 1375

Entity Framework Force CASE-WHEN column to be not nullable

I have this custom column in the stored procedure. As you can see, there is no way its value would ever be null:

cast(case when ( s.userName is not null and s.Username in ( 'super','superadmin') then 1 
    else 0 end 
    as bit)  as isSuperAdmin

But when I map it to Entity Framework, it turns into Nullable: enter image description here

Which is okay but I have to do the following, and it is ugly:

var isSuperAdmin = (!user.isSuperAdmin.HasValue) ? false: user.isSuperAdmin.Value;

is there any way to force it to be a Boolean value?

Upvotes: 4

Views: 645

Answers (1)

Martin Smith
Martin Smith

Reputation: 453618

SQL Server treats the values of most calculated expressions as nullable unless wrapped in ISNULL

This should work

ISNULL(CASE WHEN s.Username in ( 'super','superadmin') THEN CAST(1 AS BIT) END,0) as isSuperAdmin

There is no need for the s.userName is not null check. If it matches the IN it won't be NULL.

Upvotes: 4

Related Questions