auto generate in LINQ to SQL - 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.

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.

updating records from controller in web2py

I want to update some field in a record of database form controller given i know which record that is and which field that is.How do i do that?
Eg:In the table 'students' in the database there is field called gender which is either 'male' or 'female'.After adding many records,i add a new field called 'gender_description'.It should be 'girl' when gender is female and 'boy' if gender is male.I want to populate this new field for all the records automatically.How do i achieve this?
In a web2py shell, you can do:
db(db.students.gender == 'male').update(gender_description='boy')
db(db.students.gender == 'female').update(gender_description='girl')
You don't want to do this in the app code, because the above should be run only once. Also, make sure the "gender_description" field has already been added to the model definition and that a migration has been run (this will happen automatically as long as migrations are enabled).
Note, if there is always a one-to-one correspondence between "gender" and "gender_description", this may not be the best database design.
As an alternative, you might consider creating a virtual field in web2py:
db.define_table('students',
Field('gender', ...),
Field.Virtual('gender_description',
lambda r: 'boy' if r.gender == 'male' else 'girl'),
...)

How to increment primary key without using Auto Increment in 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;

Integration custom tables with pas.plugin.sqlalchemy

I'm trying to integrate custom table for authentication and role into PAS.plugin.sqlalchemy.
After customisation model.py I did manage to get my user table schema as we have in existing user table. But while installation of this pas, its create numbers tables inculding property table. Property table linked with user table through foreign key. I don't have any property table in existing scenario.
By seeing my trackback I can see while doing SQL fetch pas looks for users and property table as join query. we have data in our user (web_contact_auth) table but not in property table.
u'SELECT TOP 1 web_contact_auth.contact_number AS web
_contact_auth_contact_number, web_contact_auth.password AS web_contact_auth_pass
word, principals.id AS principals_id, principals.type AS principals_type, princi
pals.zope_id AS principals_zope_id, web_contact_auth.password_reset_token AS web
_contact_auth_password_reset_token, web_contact_auth.password_reset_expiry AS we
b_contact_auth_password_reset_expiry \nFROM principals JOIN web_contact_auth ON
principals.id = web_contact_auth.contact_number \nWHERE web_contact_auth.contact
_number = ?' ('admin',)
My questiones are:
how should I create data in property table ? Is there anyway that I can ignore property table and just fetch data from user table only.
Adavance Thanks your time for reading/reply.
Regards
WEBBYFOX
Just don't activate that plugin. I don't have a properties table. In /acl_users/plugins/manage_active, Properties Plugins, I have sql as the last option. I don't see anything else obvious.