Update object in the Entity framework that have relations - entity-framework-4.1

I am trying to update an whole entity object with relations in database in entity framework , and without success.
I am trying to do something like this:
var objectToUpdate = DAL.GetProduct(id);
// then I have collection of Comments related to this product.
// and I want to update th whole collection
objectToUpdate.Comments.Clear();
foreach(var newComment in comments){
objectToUpdate.Comments.Add(newComment);
}
What I am getting in database is duplication of all related to my products comments.
Please suggest how to update related Entities properly.
Thanks.

If you want to update a relationship between objectToUpdate and a collection of comments which are already existing in the database you need to attach the comments to context before you add them to the Comments collection of your objectToUpdate. Otherwise EF will create new comment rows in the database:
var objectToUpdate = DAL.GetProduct(id);
objectToUpdate.Comments.Clear();
foreach(var newComment in comments)
{
context.Comments.Attach(newComment);
objectToUpdate.Comments.Add(newComment);
}

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

Using Array of ids vs join table Laravel Eloquent

I am creating a Laravel Application with Eloquent connected to MySQL DBMS where I have three models:
Product
ProductGallery
File
I have also the following relations
One Product has one ProductGallery
One ProductGallery has many File
My question is:
Is it okay if I store images in ProductGallery as an array of file_ids
instead of creating a join table or having gallery_id in File model?
public function setImagesAttribute($images)
{
$this->attributes['images'] = serialize($images);
}
public function getImagesAttribute()
{
if (empty($this->attributes['images']) || is_null($this->attributes['images'])) return [];
return unserialize($this->attributes['images']);
}
I am asking this question to know if there is any side effects for this method
and in the future there might be other models related to File model (Category may have featured image file and so on).
In my opinion Better Option is creating a pivot table.. Because further when you have to join , you pull the array and you have to execute a query under a loop that is bad..

How to interact with a join table in bookshelf and knex?

I want to create an entry in a join table using bookshelf. I followed the instructions on the bookshelf website here. (Models instantiation with bookshelf and tables creation with knex).
Is there a way, upon creation of a new Book, to add values to the authors_books table WITHOUT creating an authors_books model/collection?
What should I add to this:
//Books references the Books collection that holds the Book models
var book = new Book({
title: title,
base_url: req.headers.origin
});
book.save().then(function(newBook) {
Books.add(newLink);
res.send(200, newBook);
});
Yes, of course, it's quite simple.
You need two models, Book and Author. Both have belongsToMany relationship defined and withPivot as well. withPivot lists the attributes that are in the junction table, see more here: http://bookshelfjs.org/#Model-withPivot
Afterwards, you call updatePivot, to update the attributes that are in author_book table only.

Using LINQ and Entity how do I return values of a many-to-many relationship

I have two entities, Account and Subscription with a many-to-many association between them. I can't seem to find in the tutorials anywhere how to do the following:
I want to find all the Accounts with a Subscription of type x. If I wasn't using the Entity framework I could join to the AccountSubscription table, but that isn't accessible via Entity. Do I have to create a special entity if I need to query on a many-to-many relationship?
EF should create a navigation property for a many-to-many relationship. Then you should be able to do something like this:
var accounts = from a in Accounts
where a.Subscriptions.Any(s => s.SubscriptionType == "something")
select a;
For example, I have a simple db with a many to many relationship between Products and Groups:
And EF creates the association in the model:
So I can create a query like this (here including the Groups so I can see the Category):
What about something like this:
List<Accounts> myAccounts = //get accounts;
foreach(Accounts a in myAccounts)
{
foreach(Subscriptions s in a)
{
//add it to a global list?
}
}

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).