3
Contributors
11
Replies
34
Views
2 Years
Discussion Span
Last Post by Nagarjuna_2
0

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

0

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?

Edited by JerrimePatient

0

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.

0
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");
    }
}
0

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.

1

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");
    }
}

Edited by DaveAmour

0

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:)

Edited by JerrimePatient

0

sir how to insert data when it is new and update if it alreay exists in mvc in linq to sql

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.