Entity Framework 6 with Mysql Row not insert but table increase auto_increment - entity-framework-6

i'm using EF6 to insert rows in database Mysql 8.0.26 . I've changed a column in table, after that I'm not update model in edmx . So when I try to add a new row and SaveChanges(), the save change go in error using a try and catch, but auto_increment of table increase. Someone know to understand how it can't increase auto_increment if the row can't insert :
This is the example of code :
Using e As New studio_laghezzaEntities4
Try
Dim newfasccons As New fasciconsulenza With {
.Openbyuser = idUser,
.FKcustomer = cons.CodiceCliente,
.Opendate = Date.Now,
.LastUpdateDate = Date.Now,
.LastUserUpdate = idUser,
.Praticacons = cons.CodiceFascicolo,
.Esercente = fasc.Esercente
}
e.fasciconsulenza.Add(newfasccons)
e.SaveChanges()
Dim newcons As New consulenza With {
.ProspettoOre = fasc.ProspettoOreLavoro,
.NoteConsulenza = fasc.AreaDescrittiva,
.FKuser = idUser,
.FKfasc = newfasccons.IdDoc,
.FKInterv = idtipointevento,
.DataCreazione = Date.Now
}
e.consulenza.Add(newcons)
e.SaveChanges()
Dim newconsinassoc As New consofsales With {
.FK_fasc = insertIddoc,
.FK_oursales = idsaler
}
e.consofsales.Add(newconsinassoc)
e.SaveChanges()
Catch ex As Exception
esito.inserito = False
esito.message = ex.Message
End Try
End Using

Related

Cannot insert explicit value for identity column in table 'T_PreviewDetails' when IDENTITY_INSERT is set to OFF

I got the above error while trying to insert values to the table 'T_PreviewDetails' through below code.
T_PreviewDetails objprevdet = new T_PreviewDetails();
objprevdet.Title = "preview";
objprevdet.Preview_ID = objprev.ID;
objprevdet.SelectionListDetails_ID = objSelectListDetails.ID;
objprevdet.PreviewStatus_ID = 2;
context.T_PreviewDetails.Add(objprevdet);
context.SaveChanges();
But direct inserting values to the database works fine.Also in 'T_PreviewDetails.cs'
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)] is entered.

Can I save my Linq Iqueriable to the DB using MVC 4 and EF 5?

I would like to do a query on Truck table and then save the results in the Vehicles table. Is this possible and if so can you show me an example. I've been stuck on this problem for a while.
IQueryable<TruckModel> result =
from d in db.Truck
select new TruckModel()
{
Model = d.Model
Color = d.Color;
};
var record = new Vehicles();
record.Model = model.Model;
record.Color = model.Color;
db.Points.Add(record);
db.SaveChanges();
return RedirectToAction("Index");
The pitfall is here
record.Model = model.Model;
record.Color = model.Color;
I guess what you intent is
record.Model = result.Model;

Not able to save multiple results into my table

I am working on ASP.NET MVC project. This is my code :
orderData_Entities ordertable = new orderData_Entities();
DataTable upCSV = (DataTable)TempData["UploadedCSV"];
if (isHeaderAccepted)
{
string[] data = null;
int i = 1;
foreach (DataRow dr in upCSV.Rows)
{
ObjectParameter getemail = new ObjectParameter("email", dr["email"].ToString());
ObjectParameter getpassword = new ObjectParameter("password", dr["password"].ToString());
ObjectParameter getMobile = new ObjectParameter("Mobile", dr["Mobile"].ToString());
var results = ordertable.usp_AppUpdateUserData(idSubAccount,idcategory, getemail.Value.ToString(), getpassword.Value.ToString(), getMobile.Value.ToString());
ordertable.SaveChanges();
i++;
}
}
return RedirectToAction("Index", "BulkUpload");
Here I am looping through all rows and updating results to my table. Currently what's happening here is if I have three rows with email, password and mobile, it is looping through all these three rows one by one and I can see results in debug mode, but while updating to my table, it is updating last row results to all three rows.
So can someone tell me what mistake I am doing here?
Update :
My Stored Procedure is as follows :
ALTER PROCEDURE [dbo].[usp_AppUpdateUserData]
#idSubAccount int = 0,
#idcategory int = 0,
#email nvarchar(100) =0,
#password nvarchar(50) = 0,
#Mobile nvarchar(50) = 0,
AS
BEGIN
Begin
Update tblCustomer
Set
email = #email, password = #password, mobileNo = #Mobile,
where idSubAccount = #idSubAccount and idCategory = #idcategory
END
End
GO

linq to entities - updating tables with new values not working

The code below is updating the correct values into the OBJECT_TYPES table, but the OBJECT_ITEMS table is being overwritten but I am not sure why. Can anyone help?
var templateId = Request["id"].AsInt();
var dbcontext = new STDEntities1();
var query = dbcontext.OBJECT_TYPES.Where(o => o.ID == templateId);
var template = query.FirstOrDefault();
var newItem = new OBJECT_TYPES
{
CATEGORY_ID = template.CATEGORY_ID,
COMPANY_ID = template.COMPANY_ID,
OBJECT_NAME = "** Select A Name **",
HEIGHT = template.HEIGHT,
WIDTH = template.WIDTH,
TEMPLATE = template.ID
};
foreach (var field in template.OBJECT_ITEMS)
{
newItem.OBJECT_ITEMS.Add(field);
}
dbcontext.OBJECT_TYPES.Add(newItem);
dbcontext.SaveChanges();
this is happening because you are adding field which actually is an object that is being tracked by the dataContext/dbContext and even has an id. So the values are being overwritten.
Try creating the a new field OR try detaching the field from the context and then put the Id/Primary key to 0 and try inserting it again.

Insert into multiple database tables using Linq, ASP.NET MVC

I have a rather simple scenario where I have two tables in which I want to add data. They are managed with primary key/foreign key. I want to add new data into TABLE A and then retrieve the Id and insert into TABLE B.
I can certainly do it with a stored procedure, but I'm looking at trying to do it using Linq.
What is the best approach ?
I can certainly get the ID and do two separate inserts but that doesn't certainly seem to be a very good way of doing things.
db.Table.InsertOnSubmit(dbObject);
db.SubmitChanges();
Int32 id = dbOject.Id;
//Rest of the code
Any way to elegantly do this?
Do you have the relationship defined between the 2 tables in the object relational designed? If so, you can have linq take care of assigning the ID property of the second table automatically.
Example...
Table A – Order
OrderId
OrderDate
Table B – Order Item
OrderItemId
OrderId
ItemId
Code (Using LINQ-to-SQL):
Order order = new Order();
Order.OrderDate = DateTime.Now();
dataContext.InsertOnSubmit(order);
OrderItem item1 = new OrderItem();
Item1.ItemId = 123;
//Note: We set the Order property, which is an Order object
// We do not set the OrderId property
// LINQ will know to use the Id that is assigned from the order above
Item1.Order = order;
dataContext.InsertOnSubmit(item1);
dataContext.SubmitChanges();
hi i insert data into three table using this code
Product_Table AddProducttbl = new Product_Table();
Product_Company Companytbl = new Product_Company();
Product_Category Categorytbl = new Product_Category();
// genrate product id's
long Productid = (from p in Accountdc.Product_Tables
select p.Product_ID ).FirstOrDefault();
if (Productid == 0)
Productid++;
else
Productid = (from lng in Accountdc.Product_Tables
select lng.Product_ID ).Max() + 1;
try
{
AddProducttbl.Product_ID = Productid;
AddProducttbl.Product_Name = Request.Form["ProductName"];
AddProducttbl.Reorder_Label = Request.Form["ReorderLevel"];
AddProducttbl.Unit = Convert.ToDecimal(Request.Form["Unit"]);
AddProducttbl.Selling_Price = Convert.ToDecimal(Request.Form["Selling_Price"]);
AddProducttbl.MRP = Convert.ToDecimal(Request.Form["MRP"]);
// Accountdc.Product_Tables.InsertOnSubmit(AddProducttbl );
// genrate category id's
long Companyid = (from c in Accountdc.Product_Companies
select c.Product_Company_ID).FirstOrDefault();
if (Companyid == 0)
Companyid++;
else
Companyid = (from Ct in Accountdc.Product_Companies
select Ct.Product_Company_ID).Max() + 1;
Companytbl.Product_Company_ID = Companyid;
Companytbl.Product_Company_Name = Request.Form["Company"];
AddProducttbl.Product_Company = Companytbl;
//Genrate Category id's
long Categoryid = (from ct in Accountdc.Product_Categories
select ct.Product_Category_ID).FirstOrDefault();
if (Categoryid == 0)
Categoryid++;
else
Categoryid = (from Ct in Accountdc.Product_Categories
select Ct.Product_Category_ID).Max() + 1;
Categorytbl.Product_Category_ID = Categoryid;
Categorytbl.Product_Category_Name = Request.Form["Category"];
AddProducttbl.Product_Category = Categorytbl;
Accountdc.Product_Tables.InsertOnSubmit(AddProducttbl);
Accountdc.SubmitChanges();
}
catch
{
ViewData["submit Error"] = "No Product Submit";
}

Resources