Question

I have UserName Column in my table and its is unique

I want have Linq Method that check current UserName is duplicate or not ? check UserName column in database and return boolean result

BUT I need a linq method with best performance (maybe using IQueryable)

Can anyone help me and suggest IsDuplicate method with Linq with best performance ???

thanks

Was it helpful?

Solution 2

Get the context of the database and store it in the db variable. After that you can call the method IsDuplicate which will check if there is any user with given username:

private DbContext db;

public bool IsDuplicate(string userName)
{
    return db.Users.Any(u => u.UserName == userName);
}

OTHER TIPS

You ask for it. Select (on SQL level). THe rest is a detail any programmer worth a cent can optimize, so I do not go into it (hint: optimal performance means correct indices).

YOu can do an ANY on the LINQ level, or you can ask for the object - the later may be smarter becaue "true/false" often is a bad UI and you may want to have some more information anyway.

I suggest you look at this thread

It's a any vs where discussion

Here is the content in case it gets deleted.

Where returns a new sequence of items matching the predicate.

Any returns a Boolean value; there's a version with a predicate (in which case it returns whether or not any items match) and a version without (in which case it returns whether the query-so-far contains any items).

I'm not sure about Exists - it's not a LINQ standard query operator. If there's a version for the Entity Framework, perhaps it checks for existence based on a key - a sort of specialized form of Any? (There's an Exists method in List which is similar to Any(predicate) but that predates LINQ.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top