Tuesday, April 30, 2019

Can't save new record into table using C# and Entity Framework because of NullReference error

Here is my problem:




My button click event handler:



protected void add_btn_Click(object sender, EventArgs e)
{
motorok m = new motorok();
m.marka = t1.Text;
m.tipus = t2.Text;

if (t3.Text.Length > 0)
{

m.evjarat = Convert.ToInt32(t3.Text);
}

if (t4.HasFile)
{
m.kep = t4.FileName;
}

sqlchannel.SaveNewMotor(m);
}



My method to save the data in the database:



public static void SaveNewMotor(motorok m)
{
MOTORAB_MODEL.motorok.Add(m);
MOTORAB_MODEL.SaveChanges();
}



My table:



CREATE TABLE [dbo].[motorok] 
(
[id] INT IDENTITY (1, 1) NOT NULL,
[marka] VARCHAR (50) NOT NULL,
[tipus] VARCHAR (100) NOT NULL,
[evjarat] INT NULL,
[kep] VARCHAR (100) NULL,


PRIMARY KEY CLUSTERED ([id] ASC)
);


Error: the MOTORAB_MODEL.SaveChanges() call throws a System.NullReferenceException



I think the problem has to be with the IDENTITY somehow but I can't figure out why. The method gets the object correctly with every value I want. In the DB, in my 'motorok' table the id column is set to IDENTITY and it is an integer. A select works perfectly so the database connection is fine.



Can you please help me? I've been googling for days now.




Edit:



Screenshot of the error



Edit 2:



MOTORAB_MODEL (motorab.mdf is my database file):



private static MOTORAB MOTORAB_MODEL;

static sqlchannel()
{
MOTORAB_MODEL = new MOTORAB();
}


I haven't override SaveChanges().

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...