How to increment primary key without using Auto Increment in MySql - mysql

I am having a table called Tl which consists of fields ID,Name and Course.
In my view when i click ADD DETAILS button i should be able to fill name and course and save it DB.
Here my ID is primary key.But i am not using AutoIncrement for this field.Without using increment option i should be able to save the newly added values.
Can any one suggest me how to implement this using linq query.
Thanks!

I'll suppose that you're using EntityFramework
var dbMaxId = context.TIs..Max(m => (int?) m.ID);
model.ID = dbMaxId + 1;

Related

How to edit and save multiple records in database from spring boot

My problem is simple and straight forward. I want to edit multiple records and save them in database. For editing a single record, I have used following statement in JpaRepository
DatabaseEntity findByAbcId(Integer abcId);
Here, I am trying to fetch a record from Mysql database table DatabaseEntity with respect to its column named abcId which is a foreign key of another table named ABC.
In my service class, I get this record, set its attributes and simply save it back in database like:
//Getting an existing record from database:
//Giving hardcoded value just for understanding
DatabaseEntity databaseEntity = databaseEntityRepository.findByAbcId(106);
//Setting edited fields into Model object. Except for its own id and abcId(foreign key)
databaseEntity.setCol1(value);
databaseEntity.setCol2(value);
databaseEntity.setCol3(value);
databaseEntityRepository.save(databaseEntity);
The above code will get a record and save its edited version into the database.
Now lets take a similar scenario but this time, the database is retrieving multiple records. from the database. Suppose multiple records are present against abcId column in my table. The changes in my code will be:
//Storing the result in the list as there are multiple records stored against 106
List<DatabaseEntity> databaseEntity = databaseEntityRepository.findByAbcId(106);
//What should I code here?
Now I am confused how to set values in multiple fields in a single go from spring boot. The values that I need to edit are also in another list and I tried iterating over both lists and change the database records accordingly but my approach is not a good one
//List of those records which I have edited
if(newRecordsList != null) {
//Using atomic Integer because only that can be changed within lambda expression
AtomicInteger outerLoopCounter = new AtomicInteger(0);
List<DatabaseEntity> databaseEntity = databaseEntityRepository.findByAbcId(Abc.getId());
databaseEntity.forEach(obj -> {
AtomicInteger innerLoopCounter = new AtomicInteger(0);
newRecordsList.forEach(newRecordsListObj -> {
//condition so that first record is updated according to the updated first record and other changes are updated accordingly.
if(outerLoopCounter.get() == innerLoopCounter.get()) {
obj.setName(newRecordsListObj.getName());
obj.setCondition(newRecordsListObj.getCondition());
obj.setValue(newRecordsListObj.getValue());
databaseEntityRepository.save(obj);
}
innerLoopCounter.incrementAndGet();
});
outerLoopCounter.incrementAndGet();
});
}
I know this is a very bad approach and I want to update my logic. So please help me to update these multiple records inside database.
Thanks in advance

django migrate primary OneToOneFiled ForeignKey + into composite foreign key

I've a model which is just a relation between two entities like this:
class SomeModel(models.Model):
a = OneToOneField(User,primary_key=True,...)
b = ForeignKey(Car,...)
As per design, it was correct, as I didn't want an User to have multiple Car. But in my new design, I want to accept multiple Car to an User. So I was trying something like this:
class SomeModel(models.Model):
class Meta:
unique_together = (("a", "b"),)
a = ForeignKey(User,...)
b = ForeignKey(Car,...)
But during migration, it asks me:
You are trying to add a non-nullable field 'id' to somenmodel without a default; we can't do that (the database needs something to populate existing rows).
Please select a fix:
1) Provide a one-off default now (will be set on all existing rows with a null value for this column)
2) Quit, and let me add a default in models.py
Select an option:
I just wanted to remove that foreign key from OneToOneRelation and add a new id combining both. - How to resolve this?
Delete the model and table from the database and create a new model from starting or add null=True to the given field. you must be having some data (rows) in your table and now you are creating a new column, so previous rows need something to be there in the newly created column, writing null = True will do that.

Does LINQ to SQL support Single Unit of work only or can I persist the Context and do Next operation?

I have a windows application. I am trying to insert a record through a DataContext. It has Unique identifier in the table. Even I am executing a trigger after insertion. So I am making a select query in the end of the trigger to get the auto generator number and to avoid auto-sync error. As it's a windows application I can keep the Context for longtime. When I create a new object ( for example order) and do the same previous operation, upon SubmitChanges operation, it shows cannot have duplicate key. Why can't I use this same Context to Insert the second record? Or do I need to create a new Context to insert a new Record?(Does this Unit of work Concept comes here?). Creating new Context is bad idea as I need to load all data again..
Any thought?
Some code sample to explain my situation:
CallCenterLogObjCotext = (CallCenterLogObjCotext == null ? (new CallcenterLogContext) : (CallCenterLogObjCotext));
CallDetail newCallDetailsOpenTicket = new CallDetail();
newCallDetailsOpenTicket.CallPurpose = (from callpuposelist in CallCenterLogObjCotext.CallPurposes
where callpuposelist.CallPurposeID == ((CallPurpose)(cbcallpurpose.SelectedItem)).CallPurposeID
select callpuposelist).FirstOrDefault();
Lots of settings like this ...
CallCenterLogObjCotext.CallDetails.InsertOnSubmit(newCallDetailsOpenTicket);
CallCenterLogObjCotext.SubmitChanges();
As I mentioned above, this is a click on Open Ticket button on windows form. I change the values of fname, lname and all in the textboxes available on that form and clicked the same button.
So it will call the same method again. I get the below specified error:
System.Data.Linq.DuplicateKeyException: Cannot add an entity with a key that is already in use.
You can insert more than one row with the same context object, see http://weblogs.asp.net/scottgu/archive/2007/05/19/using-linq-to-sql-part-1.aspx, http://msdn.microsoft.com/en-us/library/bb425822.aspx, and other numerous online examples. The duplicate key issue could be a linq to sql configuration issue, or a database integrity error, i.e. such as if you have a natural primary key on a table and are trying to insert a row with the same natural primary key more than once.

How to update in Linq to SqL?

every example I seen shows how to do a update query in linq to sql by doing this.
// grab entity you want to update
entity.UserId = "123"; // update the fields you want to update.
entity.Name = "bob";
Dbcontext.SubmitChanges();
I am wondering can you juse pass in a new object and have it figure it out?
Like could I do this?
Enity myEntity = new Entity();
myEntity.UserId = "123";
myEntity.Name = bob:
// grab entity record
// shove record ito the found record
// it figured out what to update and what no to update
Depending on what exactly you want to do you either need the InsertOnSubmit method, or the Attach method of the respective table (i.e. dbContext.Entities). InsertOnSubmit is used to add a record, while Attach can be used if you want to affect an UPDATE without having to first SELECT the record (you already know the primary key value)
In the case you have the dbContext available and ready, just add InsertOnSubmit:
Entity myEntity = new Entity();
myEntity.UserId = "123";
myEntity.Name = bob:
Dbcontext.InsertOnSubmit(myEntity);
Dbcontext.SubmitChanges();
As the name of the method implies, this will insert your new entity into the database on calling SubmitChanges.
Marc
If you want to do this for performance reasons then you shouldn't worry about it. Linq to Sql will cache objects locally so that just grabbing an entity by ID to modify some fields is very cheap.
It's possible to attach and persist it to the database, however you may want to set a field to check for concurrency (ie LastModified).
If you are going to use the Attach method on the data context, you need to set the primary/composite keys before you attach the entity (so you don't trigger INotifyPropertyChanging, INotifyPropertyChanged events).

auto generate in LINQ to SQL

I have a table whit 2 columns , ID and name .I set 'YES' Identity for ID column .
I want to insert data to table whit LINQ .I want to get only name column from user in my application , and then ID column fill automatic to database and I can't give data that column and fill whitout I give it .
What should I do ?
I write in c# and work whit LINQ .
So your database field already is a INT IDENTITY - right?
Next, in your LINQ to SQL designer, you need to make sure your column is set to:
Auto Generated Value = TRUE
Auto-Sync = ON INSERT
Now if you add an entry to your database, the ID will be automatically updated from the value assigned to it by the database:
YourClass instance = new YourClass();
instance.Name = "some name";
YourDataContext.InsertOnSubmit(instance);
YourDataContext.SubmitChanges();
After the SubmitChanges call, your instance.ID should now contain the ID from the database.
If you used the DBML designer, that should be setup correctly.
The 'id' will be populated after you call SubmitChanges.
Make sure your database table is setup correctly and that your ID is set as the primary key field and to auto increment. Regenerate your DBML if you need to by deleting the object and re-adding it. It should know that the ID is not needed and the auto fill it once the insert has succeeded.