g.breeze
g.breeze

Reputation: 1968

Entity Framework – linq and null values

I'd like to select TeamMembers and, if available, the related User.

public IEnumerable<RetailersFiveTeamMember> GetRetailersFiveTeamMembers(int retailLeaderID)
    {
        var members = this.EntityDataModel.DD_RetailersFiveTeamMember.Where(d => d.CMS_User1.UserID == retailLeaderID)
            .Select(d => new RetailersFiveTeamMember
        {
            DateCreated = d.DateCreated,
            Email = d.Email,
            User = new CMSUser() { UserEnabled = d.CMS_User.UserEnabled }
        }).ToArray();

        return members;

If I execute this query, I get the following error (which is expected, because the CMS_User can be null):

The cast to value type Boolean failed because the materialized value is null. Either the result type's generic parameter or the query must use a nullable type.

Then I tried it with this piece of code:

User = d.CMS_User == null ? null : new CMSUser() { UserEnabled = d.CMS_User.UserEnabled }

Then I get this exception:

Unable to create a constant value of type MsRetailClub.Core.Entities.RetailersFive.CMSUser. Only primitive types (such as Int32, String, and Guid) are supported in this context.

Can anyone show me the right way to do this? Thanks a lot!

Upvotes: 1

Views: 2960

Answers (1)

SWeko
SWeko

Reputation: 30872

I think that it's not that the d.CMS_User value is null (I think the exception would be something like 'Object reference etc...'), but that the d.CMS_User.UserEnabled is null.

This will happen if the corresponding database field is a nullable boolean. Then, you can either map it to a nullable boolean in C# (bool?) or use a default value for nulls.

I suggest changing the definiton of CMSUser to use

public bool? UserEnabled {get; set;}

but you can also do

...
User = new CMSUser()
{
  UserEnabled = d.CMS_User.UserEnabled ?? false;
}
...

Upvotes: 1

Related Questions