I inserted data in sql server using asp.net (MVC 5), and its flowing nicely, but my problem is this.
I don't want to insert in sql the exist data. How can I do it?
I inserted data in sql server using asp.net (MVC 5), and its flowing nicely, but my problem is this.
I don't want to insert in sql the exist data. How can I do it?
Can you elaborate please?
What kind of data is this?
Where is it coming from?
Are you using Entity Framework or plain Ado.net?
Thanks
I am using EF
but I want to learn plain Ado.net
also.
Product_tbl
id
name
price
1
Bag
300
2
Bag
300
How can I avoid
this kind of situation
?
I understand what duplicates are, but what I don't understand is what your data entry form and insertion code looks like.
Show me your EF code for inserting data please.
Sir. Dave, Thank you for our time. But I accidentally solve the problem in:
if (ModelState.IsValid)
{
bool bIfExist=false;
var q = from c in db.products where c.name == product.name select c;
try
{
q.ToList()[0].name.ToString();
bIfExist=true;
}
catch{}
if(bIfExist==true)
{
ModelState.AddModelError("txtName","Product Name is already exist.");
}
else
{
db.products.Add(product);
db.SaveChanges();
return RedirectToAction("Index");
}
}
Well done.
You should not use try catch like that though.
A more elegant way would be to use the linq Any function eg:
var exists = db.products.Any(p => p.Name == product.name);
Also with your linq you are selecting a product so don't use the letter c, use a p instead - its much clearer then for other people reading your code.
Here it is in a cleaner, more elegant way. It's much better this way.
if (ModelState.IsValid)
{
if(db.products.Any(p => p.Name == product.Name))
{
ModelState.AddModelError("txtName","Product Name already exists.");
}
else
{
db.products.Add(product);
db.SaveChanges();
return RedirectToAction("Index");
}
}
Hahahahaha.
I didn't know that It's posible
. :-)
thank you [Sir Dave]
. I'll use that code. It's more accurate
and precise
and it will save MORE
of my time than what I've done.
thank you again and God bless you and your whole family. O:)
Thankyou, I would definatley recomend the fluent API for linq, its very compact and elegant.
Sir. how can I insert in ado.net?
You have asked this in another post - I have replied there...
sir how to insert data when it is new and update if it alreay exists in mvc in linq to sql
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.