Valerio
Valerio

Reputation: 3614

Linq 2 SQL and custom extension method

I'm stuck on a stupid step when building my application.

I have a simple query on linq 2 sql:

var recipients = cdc.Recipients.Where(r => r.Owner == Sanitize.SanitizeUserName(context.User.Identity.Name) && r.Enabled == true && (r.DisplayName.Contains(qs) || r.EmailAddress.Contains(qs)))
                                        .Select(r => new NVC { name = r.DisplayName, value = r.EmailAddress }).ToList();

which take to the recipient's table some data and put on a custom class. All smooth here.

I need to add an extra filter on the where clause to check if the email address is valid.

I tried with a simple function but it threw a "no sql translation" exception when used it.

Digging thru the interwebs I found that I must use extensions method so I eventually build this:

public static Expression<Func<string, bool>> IsSaneEmail = y => (!string.IsNullOrEmpty(y) && Regex.IsMatch(y, emailPattern));

(where emailPattern is a regex string)

But how to apply to my query? I tried to add on the where clause

... && IsSaneEmail(r.emailAddress) && ...

or

... && r.EmailAddress.IsSaneEmail() && ...

with no luck.

I know I'm that dumb, but help me

Upvotes: 1

Views: 145

Answers (2)

Florim Maxhuni
Florim Maxhuni

Reputation: 1421

You cant do that in Linq2SQL (cant be translated into SQL) you must first convert to IEnumerable.

Upvotes: 1

silvo
silvo

Reputation: 4009

Your extension method needs to target the string class and it should be returning bool:

public static bool IsSaneEmail(this string val) {
        return !string.IsNullOrEmpty(val) && Regex.IsMatch(val, emailPattern)
    }

Once that is sorted you will be able to call this method as such:

r.EmailAddress.IsSaneEmail()

Upvotes: 0

Related Questions