插入新记录之前检查记录是否存在 [英] Check the existence of a record before inserting a new record
本文介绍了插入新记录之前检查记录是否存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用的是Ado.net实体框架是第一次,我需要检查之前,我把它插入到数据库记录的存在。优选地,如果存在AuthodSSID,而不是关键(的AuthorID)我想搜索。我使用VS2010,框架4. System.Data.Entity的是3.5.0.0。
我用Google搜索,但没有发现答案这个问题。
PublishingCompanyEntities publishContext;
publishContext =新PublishingCompanyEntities();
私人无效createNew_Click(对象发件人,EventArgs五)
{
作者newAuthor =新的作者();
newAuthor.FirstName = firstName.Text;
newAuthor.LastName = lastName.Text;
newAuthor.AuthodSSID = 20;
newAuthor.AuthorID = 10
//检查记录存在这里
publishContext.AddToAuthor(newAuthor); //插入如果它不存在
}
解决方案
要检查是否有记录存在的唯一方法是查询记录并查看是否有回来:
VAR existingAuthorCount = publishContext.Author.Count(A => a.AuthodSSID == 20 );
如果(existingAuthorCount == 0)
{
//做你插入
}
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.
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
}
解决方案
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
}
这篇关于插入新记录之前检查记录是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文