Click here to Skip to main content
15,867,704 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more: , +
i have a problem in desktop Application when i want to add a New Store
first Error
System.InvalidOperationException: 'Cannot attach an entity that already exists.'

Second Error
System.Data.SqlClient.SqlException: 'Cannot insert explicit value for identity column in table 'Store' when IDENTITY_INSERT is set to OFF.'

What I have tried:

C#
public partial class Store : DevExpress.XtraEditors.XtraForm
{
    DAL.Store store;
    public Store()
    {
        InitializeComponent();
        AddNew();
    }

    private void Store_Load(object sender, EventArgs e)
    {
       
    }

    void Save()
    {
        if (txtStore.Text.Trim()==string.Empty)
        {
            MessageBox.Show("Enter Store Name");
            return;
        }


        DAL.dbDataContext db = new DAL.dbDataContext();
        if(store.id==0)
        {
            store.id = 1;
            db.Stores.InsertOnSubmit(store);
        }
        
           db.Stores.Attach(store);
            UpdateData();
            db.SubmitChanges();
    }

    void GetData()
    {
        txtStore.Text = store.Store_Name;

    }
    void UpdateData()
    {
        store.Store_Name = txtStore.Text;

    }

    void AddNew()
    {
        store = new DAL.Store();
        GetData();
        

    }

    private void SaveBtn_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
    {
        Save();
    }

    private void NewBtn_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
    {
        AddNew();
        
    }
}
Posted
Updated 7-Dec-20 1:10am
v2
Comments
[no name] 5-Dec-20 15:21pm    
You're inserting and attaching at the same time.
ahmedbelal 5-Dec-20 17:03pm    
OH ! yes Ok What's the Solution ??
BabyYoda 7-Dec-20 9:18am    
Don't attach when it already exists. Isn't that what you error says?

The second one is also clear. You can't insert into an identity column when IDENTITY_INSERT is off.

Not to be rude, but you need to do some very basic learning. These are very simple problems if you understand how code works.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900