C# 在插入新记录之前检查记录是否存在

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9287454/
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-09 06:43:37  来源:igfitidea点击:

Check the existence of a record before inserting a new record

c#entity-framework

提问by BirdOfPrey

I'm using the Ado.net Entity Framework for the first time and I need to check if this record exist before I insert it to the database. Preferably I'd search if AuthodSSID exists and not the key (AuthorID). I'm using VS2010, Framework 4. System.Data.Entity is 3.5.0.0.

我是第一次使用 Ado.net 实体框架,我需要在将它插入数据库之前检查该记录是否存在。我最好搜索 AuthodSSID 是否存在而不是密钥(AuthorID)。我使用的是 VS2010,框架 4。System.Data.Entity 是 3.5.0.0。

I googled, but found no answer for this question.

我用谷歌搜索,但没有找到这个问题的答案。

PublishingCompanyEntities publishContext;
publishContext = new PublishingCompanyEntities();

private void createNew_Click(object sender, EventArgs e)
{
    Author newAuthor = new Author();
    newAuthor.FirstName = firstName.Text;
    newAuthor.LastName = lastName.Text;
    newAuthor.AuthodSSID = 20;
    newAuthor.AuthorID = 10
//Check if record exist here
    publishContext.AddToAuthor(newAuthor);//insert if does not exist

}

采纳答案by Jacob

The only way to check if a record exists is to query the record and see if anything comes back:

检查记录是否存在的唯一方法是查询记录并查看是否有任何返回:

var existingAuthorCount = publishContext.Author.Count(a => a.AuthodSSID == 20);
if (existingAuthorCount == 0) 
{
    // Do your insert
}

回答by M.Babcock

Something like this should work:

这样的事情应该工作:

if (publishContext.Author.Select(a => a.AuthodSSID).Where(id => id == 20).Take(1) == null)
    // It doesn't exist
else
    // It does exist

Based on my (albeit fundamental) understanding this should produce a SQL statement equivalent to:

根据我的(尽管是基本的)理解,这应该产生一个等效于的 SQL 语句:

SELECT TOP(1) AutodSSID FROM Author WHERE AuthodSSID = 20;


Another simpler approach may be to use the Anyextension method:

另一种更简单的方法可能是使用Any扩展方法:

if (!publishContext.Author.Any(a => a.AuthodSSID == 20))
    // Put your insert logic here.

回答by gideon

All you need to do is search (with linq) for an author with that ID.

您需要做的就是(使用 linq)搜索具有该 ID 的作者。

The Where()method will return a collection of authors you only need one, so you use FirstOrDefault()which returns the first element or null if there is nothing. You could also use SinglOrDefaultwhich throws an exception if there is more than one element in the list, or just returns that element.

Where()方法将返回您只需要一个作者的集合,因此您可以使用FirstOrDefault()which 返回第一个元素,如果没有,则返回 null。SinglOrDefault如果列表中有多个元素,您也可以使用which 抛出异常,或者只返回该元素。

Seems @Jacob has an excellent, more efficient approach!

似乎@Jacob 有一个出色的、更有效的方法!

var author = publishContext.Authors.Where
                               (a=>a.AuthodSSID == 10).FirstOrDefault();
if(author == null) //none exist
{//don't bother creating one unless you need to..
    Author newAuthor = new Author();
    newAuthor.FirstName = firstName.Text;
    newAuthor.LastName = lastName.Text;
    newAuthor.AuthodSSID = 20;
    newAuthor.AuthorID = 10
    publishContext.AddToAuthor(newAuthor);//insert if does not exist
}

回答by Ryk

I personally prefer this approach from a .NET point of view. It is cleaner and if you care about speed (in .NET), it is more efficient, however the SQL is not that flash;

从 .NET 的角度来看,我个人更喜欢这种方法。它更干净,如果你关心速度(在 .NET 中),它会更有效率,但是 SQL 不是那么快;

private bool CheckIfEntityRecordExists(Entity e)
{
    var retVal = false;
    using (var db = new EntityContext())
    {
        retVal = db.AdviserClients.Any(a => a.Id == e.Id);
    }
    return retVal;
}

So for a efficient SQL statement, the following is the best:

所以对于一个高效的 SQL 语句,以下是最好的:

private bool CheckIfEntityRecordExists(Entity e)
{
    var retVal = false;
    using (var db = new EntityContext())
    {
        retVal = db.AdviserClients.Count(a => a.Id == e.Id) > 0;
    }
    return retVal;
}

回答by Aleksandr Khomenko

There is so called "upsert" operation available in EF v5.0+

EF v5.0+ 中提供了所谓的“upsert”操作

publishContext.Author.AddOrUpdate(x => x.Id, newAuthor)

AddOrUpdate can be found in the "System.Data.Entity.Migrations" namespace, so don't forget to add:

AddOrUpdate 可以在“System.Data.Entity.Migrations”命名空间中找到,所以不要忘记添加:

using System.Data.Entity.Migrations;

The AddOrUpdate operation is not atomic. But *if (existingAuthorCount == 0) {// Do your insert} isn't also.

AddOrUpdate 操作不是原子操作。但是 *if (existingAuthorCount == 0) {// Do your insert} 也不是。