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

我第一次使用Ado.netentity framework,我需要在将其插入数据库之前检查该记录是否存在。 我最好搜索是否存在AuthodSSID而不是密钥(AuthorID)。 我正在使用VS2010,Framework 4. System.Data.Entity是3.5.0.0。

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

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 } 

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

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

像这样的东西应该工作:

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

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

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

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

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

从.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; } 

因此,对于有效的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; } 

EF v5.0 +中有所谓的“upsert”操作

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

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

 using System.Data.Entity.Migrations; 

AddOrUpdate操作不是primefaces操作。 但是* if(existingAuthorCount == 0){//你的插入}也不是。

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

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

似乎@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 }