Getting the error “cannot add an entity that already exists.” while inserting a table's value in to DB without procedure

前端 未结 5 1605
谎友^
谎友^ 2021-01-21 05:15

I am inserting a list of records to the DB table with Linq to sql like this:

//my DataContext Class
 using (VTMMedicalDBDataContext objVTMMedicalDBDataContext =          


        
相关标签:
5条回答
  • 2021-01-21 05:53

    Finally After Much hassle I got my answer with a new concept..

    For all those facing similar problems,here is a clear solution:

    You need to create the object of the 'Table' class(which object you want to update in DB), inside the loop(*for each,for or any other..)so that same record is not updated and each object uses a different memory location(as the local instance gets destroyed inside the loop only..)*

    0 讨论(0)
  • 2021-01-21 05:53

    I have a primary key but I already made it as AutoGenerated as true in DBML

    That's fine, however, have you made the field auto-generated at database level? AutoGenerated at DBML level won't actually generate any values for you, it just indicates to the model that the value will be generated by the storage provider (so it probably omits sending it as part of the query).

    0 讨论(0)
  • 2021-01-21 05:53

    As an alternative you can call stored procedure inside db which will do the insert: Updating database by using stored procedures.

    0 讨论(0)
  • 2021-01-21 05:53

    using (VTMMedicalDBDataContext objVTMMedicalDBDataContext = new VTMMedicalDBDataContext()) { ReadOnlyCollection objTimeZones = null;

     objTimeZones = TimeZoneInfo.GetSystemTimeZones();
    
     if (objTimeZones.Count > 0)
     {
         //List<TimeZoneMaster> listTimeZones = new List<TimeZoneMaster>();
    
    
         foreach (var timezone in objTimeZones.ToList())
         {
              TimeZoneMaster objTimeZoneMaster = new TimeZoneMaster();
    
             objTimeZoneMaster.TimeZoneName = timezone.DisplayName;
    
             var localName = timezone.DisplayName;
    
             objTimeZoneMaster.TimeZoneOffsetInMinutes = Convert.ToInt32(timezone.BaseUtcOffset.TotalMinutes);                      
    
    
             objVTMMedicalDBDataContext.TimeZoneMasters.InsertOnSubmit(objTimeZoneMaster);
             objVTMMedicalDBDataContext.SubmitChanges();
    
    
         }
    
     }
    

    }

    0 讨论(0)
  • 2021-01-21 06:05

    You have to update table to have that column with identity value (autoincrement).

    Then update your DBML model-> Delete the table from DBML designer, refresh your table at server explorer and drag and drop the table object again. Generate the project and it should work nice.

    0 讨论(0)
提交回复
热议问题