Search code examples
c#.netentity-frameworkvisual-studio-2013mdf

Unable to Insert data in an .mdf using Entity Framework


I am trying to insert Data in an .mdf file using Entity Framework but there is no data saved in the database. (I am using VS 2013)

Code Against the Button is

private void BtnSubmit_Click(object sender, RoutedEventArgs e)
    {
        Product record = new Product();
        record.ProductName = txtProductName.Text;
        AzadIndustryEntities1 Db = new AzadIndustryEntities1();
        Db.Products.Add(record);
        Db.SaveChanges();
        MessageBox.Show("Record Inserted");
    }

SQL against Products Table is

CREATE TABLE [dbo].[Products] (
[ProductID]          INT          IDENTITY (1, 1) NOT NULL,
[ProductName]        VARCHAR (50) NULL,
[ProductQuantity]    INT          NULL,
[PricePerUnit]       VARCHAR (50) NULL,
[ProductDescription] VARCHAR (50) NULL,
[UserID]             INT          NULL,
[CustomerID]         INT          NULL,
CONSTRAINT [PK_Products] PRIMARY KEY CLUSTERED ([ProductID] ASC),
CONSTRAINT [FK_Products_ToTable_Customer] FOREIGN KEY ([CustomerID]) REFERENCES [dbo].[Customer] ([CustomerID]),
CONSTRAINT [FK_Products_ToTable_Products] FOREIGN KEY ([UserID]) REFERENCES [dbo].[Users] ([UserID])

);


Solution

  • My problem is solved. Going to explain it so that it could help others also.

    As the default property of .mdf file Copy to Output Directory is Copy always so when we debug our program a copy of the .mdf file is copied in the debug folder which is in the bin folder (Select Show All Files in Solution Explorer to view the bin folder) so, whatever changes we make in database through code it is saved in the copied .mdf that is in the debug folder. When we debug our program again the same steps are performed again and the previous database is overwritten. To prevent such happening the property of .mdf file mentioned above should be set to Copy if newer so, if there is any change in the model only then the .mdf will be overwritten.