-1

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

Hamed F
  • 800
  • 3
  • 11
  • 23
  • 1
    What have you tried and benchmarked? Has this shown to be a noticeable bottle-neck in your code? Is it obviously too slow now? Why are you worrying about this? – Moo-Juice Apr 25 '14 at 09:44
  • 2
    Did you try `System.Linq Any()`? [Click](http://msdn.microsoft.com/en-us/library/vstudio/bb534972(v=vs.100).aspx) – Loetn Apr 25 '14 at 09:45
  • I must check UserName in validation layer of my application so I need an IsDuplicate Linq Method for checking before any insert with best performance – Hamed F Apr 25 '14 at 09:46

3 Answers3

1

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.

TomTom
  • 61,059
  • 10
  • 88
  • 148
0

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);
}
Abbas
  • 14,186
  • 6
  • 41
  • 72
0

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.)

Community
  • 1
  • 1
Kevin Cloet
  • 2,956
  • 1
  • 19
  • 36
  • 1
    While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. – nsgocev Oct 01 '15 at 15:01
  • 1
    I quoted the text and added it to the post – Kevin Cloet Oct 02 '15 at 06:34