Update rows if their keys are in a set - sql-server

I have a table in SQL Server with a composite primary key and a set of keys of rows that need to be updated. Is it possible to update these rows (e.g. do thing like this) using Entity Framework Plus or anything else?
I want something like
ctx.Users.Where(x => MySet.Contains(new { x.Col1, x.Col2 }))
.Update(x => new User() { IsSoftDeleted = 1 });

Related

Unable to update the EntitySet '' because it has a DefiningQuery and no <DeleteFunction>

The entire error message is below:
Unable to update the EntitySet '' because it has a DefiningQuery and no element exists in the element to support the current operation.
So everything I've read is talking about not having a Primary Key. However I have a primary key. I have a composite primary key of a couple fields. Is it not possible to delete a record with entity framework with a composite primary key on the table? If this is the case it seems silly to add 1 field just for this purpose. What are my other options?
Here is what I'm doing (an example)
var recs = (from a in dbContext.mytable where a.State == 'Texas' select a);
foreach(var d in recs)
{
dbContext.myTable.Remove(d);
}
dbContext.SaveChanges(); // ERROR
Imagine that mytable has 10 fields and 4 or them make up the PK.

How to create and add initial data row to new table using Entity Framework 6 Code First migrations

Working with Entity Framework 6 Code First migrations, I need to add a new table to the DB and then add a foreign key to that new table in an existing table (with lots of data in it).
Since the existing table already has lots of data in it, and the FK to the new table will be NOT NULL, I need to be able to add a row to the new table and then add the key (identity) from this row to all of the existing rows in the "old" table before it is made NOT NULL.
Is there a way to do this in code, so that it will be performed every time I use the Update-Database command, or do I have to manually change the genrated SQL-script?
The existing table/class is named: Certificate
The new table/class is named: CertificateRegistry
The relationship is CertificateRegistry(One)-->Certificate(many).
New column in Certificate would be CertificateRegistryId as a NOT NULL foreign key.
To clarify: the creation of tables and relationships is not a problem, but how I via the code can add a row to new table, and then update existing rows in the old table with the generated identity.
I have tried to search for answers to this without luck, so if you think this is a duplicate, please post a link to the answer.
You have to create the new foreign key as a nullable column, then run sql to update the values, then change the column to not nullable.
Create your model with the non-nullable key -> Add-Migration -> Alter the AddColumn statement by changing nullable from true to false -> Add your Sql("") -> add an AlterColumn statement
The code in your migrations should include something like this:
AddColumn("dbo.Foos", "NewForeignKey", c => c.Int(nullable: true));
Sql("Update dbo.Foos set NewForeignKey = ...");
AlterColumn("dbo.Foos", "NewForeignKey", c => c.Int(nullable: false));

Creating new record if the id is not in db

I am working on a cakephp 2.x , I want to create a new row or record if the userid is not present in db otherwise update the record, but the problem is: it is not updating the current record. It is creating the record with the userid "0" I dont know the problem is. If is not finding the record it should create a record with the userid which I am giving.
public function activeNoStatus(){
$this->loadModel('Status');
$userid = $this->request->data('idUser');
$notify = $this->request->data('notify');
$data = array();
$data['activeNo'] = $notify;
$count = $this->Status->findUserId($userid);
if($count>0){
$this->Status->id = $userid;
$this->Status->save($data);
echo "update";
}else{
//create new row
$datanew=array();
$this->Status->id = $userid;
$this->request->data['Status']['activeNo']=$notify;
$this->Status->save($this->request->data);
echo "ok";
}
}
It seems idUser field is not autoincrement, In cakePHP documentaion :
All tables with which CakePHP models interact (with the exception of
join tables), require a singular primary key to uniquely identify each
row. If you wish to model a table which does not have a single-field
primary key, CakePHP’s convention is that a single-field primary key
is added to the table. You have to add a single-field primary key if
you want to use that table’s model.
Rather than using an auto-increment key as the primary key, you may
also use char(36). Cake will then use a unique 36 character uuid
(String::uuid) whenever you save a new record using the Model::save
method.
So you should make idUser autoincrement Primary key.

delete function not working cakephp

i am working on a Cakephp 2.x ...i want to delete a single record from the database
i have a table in my database called Image .. which contain following fields..
idImage,User_id,filename,filesize,filemime
I would like to delete the single record with idImage=imageid
delete * from posts where imageid = 3'
i am doing this ..image id now has a value 4
$this->Image->imageId = $imageId;
if($this->Image->delete()){
echo "successfull";
}else{
echo "not";
}
but the code is not working .not deleting the record from db
id, not imageId
Setting imageId on the Image model will have no effect at all. If the model's primary key is not id it's necessary to configure the model so that Cake is aware of this and will use your chosen primary key field instead of id.
<?php
class Image extends AppModel {
$primaryKey = 'imageId';
Irrespective of the value of the primary key, the property to set to use the syntax in the question is:
$this->Image->id = $imageId;
if($this->Image->delete()){
This will attempt to delete the image with the given $imageId.
Alternatively just pass it to the delete function:
if($this->Image->delete($imageId)){
Deleting without a primary key
If the objective is to delete by a value that isn't the primary key, either look for it first:
$id = $this->Image->field('id', array('imageId' => $imageId));
if ($id && $this->Image->delete($id)) {
...
Or use deleteAll:
// delete 1 or more records with a matching field value
$this->Image->deleteAll(array(
'imageId' => $imageId
));

How can I model an is-a relationship with DBIx::Class?

With the following (simplified) MySQL table definitions:
create table items (
item_id int unsigned auto_increment primary key,
purchase_date date
) engine = innodb;
create table computers (
item_id int unsigned primary key,
processor_type varchar(50),
foreign key item_fk (item_id) references items (item_id)
on update restrict on delete cascade
) engine = innodb;
create table printers (
item_id int unsigned primary key,
is_duplex boolean,
foreign key item_fk (item_id) references items (item_id)
on update restrict on delete cascade
) engine = innodb;
Being new to DBIx::Class, I would like to model an inheritance relationship between database entities (computers and printers both being items), but with the provided belongs_to relationship type, this seems to be awkward, because the association with the base class is not hidden, so one must still manually create entities for both classes, and access to base class attributes in the derived classes is different from accessing their own attributes.
Is there an elegant solution which would allow me to say:
$printer = $printer_rs->create({purchase_date => $date, is_duplex => 0});
or (on a fetched printer row):
$date = $printer->purchase_date;
$duplex = $printer->is_duplex;
?
You can use the proxy attribute on a relationship to enable the accessors -- it's documented in add_relationship of DBIx::Class::Relationship::Base and you can use it with belongs_to like:
__PACKAGE__->belongs_to(
'item' => 'MyApp::Schema::Item',
'item_id',
{ proxy => [ qw/purchase_date/ ] }
);
which will make all of your Printer objects have purchase_date accessors that refer to the associated Item object.
As for create, you can't do it without overriding new_result, which is actually pretty easy. You just have to take advantage of the create-from-related behavior to turn
->create({
is_duplex => 1,
purchase_date => $dt,
})
into
->create({
is_duplex => 1,
item => {
purchase_date => $dt,
},
})
Or you could just foist the knowledge of what columns are in item off on your users and have them provide that hashref directly ;)

Resources