C# 你如何检查记录是否存在

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13830928/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 09:55:41  来源:igfitidea点击:

How do you check if Record exists

c#asp.netlinqentity-framework

提问by Hymanncoke

I have a form that does an insert. I want to see if the record already exists in the database to prevent duplicates. I am a little unsure of when this has to go down. In the codebehind for the controls that is the form or in the Class that I call on to perform the insert. Below is the class that is where I am thinking it goes.

我有一个可以插入的表单。我想查看该记录是否已存在于数据库中以防止重复。我有点不确定什么时候必须下降。在作为表单的控件的代码隐藏中或在我调用以执行插入的类中。下面是我认为它去的班级。

public class AddContacts
{
    public int AddContact(string ContactName)
    {
        var myContact = new Solutions.Models.Contact();

        myContact.ContactName = ContactName;

        ItemContext _db = new ItemContext();

        _db.Contacts.Add(myContact);
        _db.SaveChanges();
        return myContact.ContactID;
    }
}

I have seen it done with If statements that use .Any()but i cannot get it work right. Nor do I understand what it would need to return in order for me to post a error message Contact Name already exists.

我已经看到它使用 If 语句完成,.Any()但我无法使其正常工作。我也不明白它需要返回什么才能发布错误消息Contact Name already exists

采纳答案by siger

You could use the Any method like this:

您可以像这样使用 Any 方法:

bool contactExists = _db.Contacts.Any(contact => contact.ContactName.Equals(ContactName));

if (contactExists)
{
    return -1;
}
else
{
    _db.Contacts.Add(myContact);
    _db.SaveChanges();
    return myContact.ContactID;
}

The method calling AddContact would check the return value and decide whether to display an error or confirmation message to the user.

调用 AddContact 的方法将检查返回值并决定是否向用户显示错误或确认消息。

回答by Arash Emami

Do a check like this:

做这样的检查:

bool doesExistAlready = _db.Contacts.Any(o => o.ContactName == ContactName);

If that doesn't work, try this:

如果这不起作用,请尝试以下操作:

bool doesExistAlready = _db.Contacts.Count(o => o.ContactName == ContactName) > 0;

Turn on SQL tracing/debugging so you see the actual sql being produced.

打开 SQL 跟踪/调试,以便您看到正在生成的实际 sql。

回答by user5634773

This too can help.

这也可以提供帮助。

bool doesExistAlready = _db.Contacts.Count(o => o.ContactName == ContactName) > 0;