Click here to Skip to main content
15,902,112 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i was trying Data insert using Linq to SQl in asp.net C#.

I got problem with Primery key, How to write code for this.. pls help me..

What I have tried:

C#
protected void Button4_Click(object sender, EventArgs e)
    {
        linkdbDataContext DB = new linkdbDataContext();
        subject TC = new subject();

// "NOS" is the primerykey and autoincriment field, define in Sql Server.
        TC.Nos = true;
        TC.CLASSS = txclass.Text;
        TC.Subjects = txsubject.Text;
        TC.lesson = txlesson.Text;
        TC.chapter = txchapter.Text;

        DB.subjects.InsertOnSubmit(TC);
        DB.SubmitChanges();  

    }
Posted
Updated 30-Nov-16 9:17am
v2
Comments
Ehsan Sajjad 30-Nov-16 14:53pm    
what is the datatype of it in sql server?

There is some contradiction in what you have here...
C#
// "NOS" is the primerykey and autoincriment field, define in Sql Server.
TC.Nos = true;

So either NOS is a SID (so numeric) or it is boolean (as you set it to 'true')...
In any case you need not and can not set the value for an auto-increment (SID) field in SQL, you have to left it to the SQL engine...
Set all the other field and insert you new record, SQL will assign the next value to the auto-increment field...
 
Share this answer
 
I gues this your table:

Subject

Nos Int (identity|autoincrement)
CLASSS varchar
Subjects varchar
lesson varchar
chapter varchar



if the Nos Field is integer:

1- Change the datatype from the entity Subject, It looks like a bool, change bool for int

2- Change:
C#
protected void Button4_Click(object sender, EventArgs e)
    {
        linkdbDataContext DB = new linkdbDataContext();
        subject TC = new subject();
 
        // "NOS" is the primerykey and autoincriment field, define in Sql Server.
        // TC.Nos = true;
        TC.Nos = 0 //Zero the autoincrement should work, if not try comment this line
        TC.CLASSS = txclass.Text;
        TC.Subjects = txsubject.Text;
        TC.lesson = txlesson.Text;
        TC.chapter = txchapter.Text;
 
        DB.subjects.InsertOnSubmit(TC);
        DB.SubmitChanges();  
 
    }
 
Share this answer
 
Comments
Member 11917879 1-Dec-16 9:43am    
Thank u so much boss..
It is working
Cristina Carrasco Angulo 1-Dec-16 13:04pm    
Very nice :)
Cristina Carrasco Angulo 1-Dec-16 13:03pm    
Very nice :)

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