[英]validation on import from Excel to Database using ADO.net
I need to Append data from Excel to Database so I need to check for validation in Excel columns like if dr[0]
is number or not and if any row in Excel is repeated in the database skip it and add only new records: 我需要将数据从Excel追加到数据库,所以我需要检查Excel列中的验证,例如dr[0]
是否为数字,以及数据库中是否重复了Excel中的任何行,请跳过它并仅添加新记录:
MaamoonKhalidIssueEntities db = new MaamoonKhalidIssueEntities();
foreach (DataTable table in result.Tables)
{
foreach (DataRow dr in table.Rows)
{
Person addtable = new Person()
{
nparent =Convert.ToInt32(dr[0]),
ncode = Convert.ToString(dr[1]),
nname = Convert.ToString(dr[2])
};
db.People.Add(addtable);
}
I Can't check on dr[0]
because its object 我无法检查dr[0]
因为它的对象
You can write a ValidateNewPerson-Method. 您可以编写ValidateNewPerson-Method。 This method tries to fetch a person with the same ncode from the DB. 此方法尝试从数据库中获取具有相同ncode的人。 If this succeeds, the record is not valid, if not, the person can be added: 如果成功,则该记录无效,如果无效,则可以添加此人:
public bool ValidateNewPerson(Person newPerson, MaamoonKhalidIssueEntities db)
{
var dbPerson = db.People.Where(e => e.ncode == newPerson.ncode).FirstOrDefault();
if (dbPerson == null)
return true;
else
return false;
}
Now you can call this method in your foreach: 现在,您可以在foreach中调用此方法:
foreach (DataRow dr in table.Rows)
{
Person addtable = new Person()
{
nparent =Convert.ToInt32(dr[0]),
ncode = Convert.ToString(dr[1]),
nname = Convert.ToString(dr[2])
};
if (ValidateNewPerson(addtable, db))
db.People.Add(addtable);
}
If you want to use a Linq-Method, you can use Any, to request if any record in your db matches your criteria: 如果要使用Linq方法,则可以使用Any来请求数据库中的任何记录是否符合您的条件:
foreach (DataRow dr in table.Rows)
{
Person addtable = new Person()
{
nparent =Convert.ToInt32(dr[0]),
ncode = Convert.ToString(dr[1]),
nname = Convert.ToString(dr[2])
};
if (!db.People.Any(p => p.ncode == addtable.ncode))
db.People.Add(addtable);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.