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

eqoofvh9  于 2021-08-09  发布在  Java
关注(0)|答案(5)|浏览(485)

我是第一次使用ado.net实体框架,在将此记录插入数据库之前,我需要检查它是否存在。我最好搜索authodssid是否存在,而不是键(authord)。我使用的是vs2010,framework4。system.data.entity为3.5.0.0。
我搜索了一下,但没有找到这个问题的答案。

  1. PublishingCompanyEntities publishContext;
  2. publishContext = new PublishingCompanyEntities();
  3. private void createNew_Click(object sender, EventArgs e)
  4. {
  5. Author newAuthor = new Author();
  6. newAuthor.FirstName = firstName.Text;
  7. newAuthor.LastName = lastName.Text;
  8. newAuthor.AuthodSSID = 20;
  9. newAuthor.AuthorID = 10
  10. //Check if record exist here
  11. publishContext.AddToAuthor(newAuthor);//insert if does not exist
  12. }
rmbxnbpk

rmbxnbpk1#

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

  1. var existingAuthorCount = publishContext.Author.Count(a => a.AuthodSSID == 20);
  2. if (existingAuthorCount == 0)
  3. {
  4. // Do your insert
  5. }
aelbi1ox

aelbi1ox2#

这样的方法应该有用:

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

根据我的理解(尽管是基本的),这应该会产生一个sql语句,相当于:

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

另一个更简单的方法是使用 Any 扩展方法:

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

q5iwbnjs3#

从.net的Angular 来看,我个人更喜欢这种方法。它更干净,如果你关心速度(在.net中),它更高效,但是sql不是那么快;

  1. private bool CheckIfEntityRecordExists(Entity e)
  2. {
  3. var retVal = false;
  4. using (var db = new EntityContext())
  5. {
  6. retVal = db.AdviserClients.Any(a => a.Id == e.Id);
  7. }
  8. return retVal;
  9. }

因此,对于高效的sql语句,以下是最好的:

  1. private bool CheckIfEntityRecordExists(Entity e)
  2. {
  3. var retVal = false;
  4. using (var db = new EntityContext())
  5. {
  6. retVal = db.AdviserClients.Count(a => a.Id == e.Id) > 0;
  7. }
  8. return retVal;
  9. }
展开查看全部
0vvn1miw

0vvn1miw4#

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

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

addorupdate可以在“system.data.entity.migrations”命名空间中找到,因此不要忘记添加:

  1. using System.Data.Entity.Migrations;

addorupdate操作不是原子的。但是*if(existingauthorcount==0){//do your insert}也不是。

pb3skfrl

pb3skfrl5#

你所需要做的就是(用linq)搜索一个有这个id的作者。
这个 Where() 方法将返回您只需要一个作者的集合,因此使用 FirstOrDefault() 返回第一个元素,如果没有则返回null。你也可以用 SinglOrDefault 如果列表中有多个元素,则抛出异常,或者仅返回该元素。
似乎@jacob有一个很好的,更有效的方法!

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

相关问题