简体   繁体   中英

What's the best way to test for a preexisting record in Entity Framework?

My MVC project uses entity framework to handle communication with the database.

The web application needs the ability to verify that a value provided by the user via a web form does not exist in the database before the SaveChanges method is invoked. An index on the database table prevents duplicate values. I don't want to rely on the SQL exception for finding out there's a problem with the new value.

What I did was to use a Linq statement that retrieves any records that have a ContactKey property with the submitted value. Then I use the Count property of the entity. If it returns 0, then I assume that the new value is unique. Here's the code snippet:

// newKey is the value provided by user
var existing = from c in db.Contacts where c.ContactKey == newKey select c;
if (existing.Count()==0)
{
    isUnique = true;
}

While this seems to work as intended, I'm new to Linq and am not sure if this is the best way to go.

I would appreciate any confirmation or suggestions for improvement.

Don Langham

使用Enumerable.Any

bool ifExist = db.Contacts.Any(r=> r.ContactKey == newKey);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM