I'm new to Entity frameworks and got some questions. I've got an EFcore project where there needs to be a database around users, with roles, groups,..
First I had Razor CRUD pages where everything worked. I could add, update and delete users, roles, groups,... But along the way I realised that I rahter needed a SwaggerUI so I could use that API for an other frontend project.
So I changed the razor pages to Swagger and for some reason the database doesn't change when I Update, delete or post something. Without any warnings. I even get succes codes back as feedback.
But the action doesn't really go through.
(When I delete, it says deteled but record is still the same. Same with Update and with a post, it says that the creation succeeded but the new record is not in my database.
I can view all records with Get & specific Records with Get:ID so I'm kind of lost why my update, post or delete action don't work.
I'm kind of new in this area so any feedback is much appreciated.
Thanks in advance.
Try to update/delete/post a record in db. Always gives
UserController : ( this worked with the Razor pages but not with the swagger page)
[HttpDelete("{id}")]
public ActionResult<User> Delete(int id)
{
var user = _userRepo.Get(id);
if(user != null)
{
_userRepo.Delete(id);Console.WriteLine("is deleted.");
}
else
{
return NotFound();
}
return NoContent();
}
[HttpPost()]
public IActionResult Add([FromBody] UserCreateViewModel model)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var newUser = new User
{
FirstName = model.FirstName,
LastName = model.LastName,
Email = model.Email,
Platform = model.Platform,
Is_enabled = model.Is_enabled,
};
Console.WriteLine(newUser);
_userRepo.Add(newUser);
return CreatedAtAction(nameof(Get), new { newUser.Id }, newUser);
}
Note: The Console.WriteLine("is deleted."); does run and is shown in the console. But it doesn't delete the record.
In Entity Framework, the SaveChanges() method internally creates a
transaction and wraps all INSERT, UPDATE and DELETE operations under
it. Multiple SaveChanges() calls, create separate transactions,
perform CRUD operations and then commit each transaction.
https://www.entityframeworktutorial.net/entityframework6/transaction-in-entity-framework.aspx#:~:text=In%20Entity%20Framework%2C%20the%20SaveChanges,and%20then%20commit%20each%20transaction.
Related
I am currently setting up a new project using Laravel 8. Out of the box, Laravel is configured to use auto-incrementing ID's for the user's ID. In the past I have overrode this by doing the following.
Updating the ID column in the user table creation migration to
$table->uuid('id');
$table->primary('id');
Adding the following trait
trait UsesUUID
{
protected static function bootUsesUUID()
{
static::creating(function ($model) {
$model->{$model->getKeyName()} = (string) Str::orderedUuid();
});
}
}
Adding the following to the user model file
use UsesUUID;
public $incrementing = false;
protected $primaryKey = 'id';
protected $keyType = 'uuid';
On this new project, I did the same as above. This seems to break the login functionality. When the email and password are entered and submitted, the form clears as though the page has been refreshed. Thing to note is there are no typical validation error messages returned as would be expected if the email and/or password is wrong.
To check that the right account is actually being found and the password is being checked properly, I added the following code to the FortifyServiceProvider boot method. The log file confirms that the user is found and the user object dump is correct too.
Fortify::authenticateUsing(function(Request $request) {
\Log::debug('running login flow...');
$user = User::where('email', $request->email)->first();
if ($user && Hash::check($request->password, $user->password)) {
\Log::debug('user found');
\Log::debug($user);
return $user;
}
\Log::debug('user not found');
return false;
});
Undoing the above changes to the user model fixes the login problem. However, it introduces a new problem that is the login will be successful but it wont be the right account that is logged in. For example, there are 3 accounts, I enter the credentials for the second or third account, but no matter what, the system will always login using the first account.
Anyone have any suggestions or ideas as to what I may be doing wrong, or if anyone has come across the same/similar issue and how you went about resolving it?
Thanks.
After digging around some more, I have found the solution.
Laravel 8 now stores sessions inside the sessions table in the database. The sessions table has got a user_id column that is a foreign key to the id column in the users table.
Looking at the migration file for the sessions table, I found that I had forgot to change the following the problem.
From
$table->foreignId('user_id')->nullable()->index();
To
$table->foreignUuid('user_id')->nullable()->index();
This is because Laravel 8 by default uses auto incrementing ID for user ID. Since I had modified the ID column to the users table to UUID, I had forgotten to update the reference in the sessions table too.
We have a web application that users log into and consume our products. From this application, we'd like to have a form that users can submit to create cases in our Salesforce instance. I'm looking for a REST API endpoint that I can POST the new case information to, which will then create a new case record in Salesforce. I'm a little confused on the right way to approach this based on the Salesforce docs (Apex, Lightning Platform, Force.com, etc.). Has anyone implemented this or can share the right approach?
Easiest way to would be to create a force.com site, which is essentially a visualforce page. Your page can then use a controller to read values and create Cases.
For e.g. this visualforce page updates a custom object record by using id passed in url:
<apex:page controller="MyService"></apex:page>
#RestResource(urlMapping='/myservice')
global class MyService {
#HttpGet
global static void doGet() {
RestContext.response.addHeader('Content-Type', 'text/plain');
String id = RestContext.request.params.get('id');
abc__c veh = [select name, abc__c from abc__c where id =:id];
if(veh!=null)
{
veh.abc__c = true;
try {
update veh;
} catch (DMLException e) {
RestContext.response.responseBody = Blob.valueOf('DML ERROR');
}
RestContext.response.responseBody = Blob.valueOf('OK');
}
else
RestContext.response.responseBody = Blob.valueOf('FAIL');
}
}
I am using Gmail, Salesforce integration app, using which I can save an interested mail into Salesforce Activity History of a Contact. Now, as soon as I receive the activity history, I want to save this into a custom field, named EmailBody__c.
Can any provide me a solution to it? Thanks in advance.
UPDATE: I have tried with the below trigger but have no luck.
trigger EmailBodyTrigger on Contact(before update) {
Contact[] contacts = Trigger.new;
for(Contact c : contacts) {
try {
ActivityHistory ah = c.ActivityHistories;
if(ah != null) {
contact.EmailBody__c = 'Hello Ram, How are you';
}
} catch(System.QueryException e) {
// no trigger call
}
}
}
I have experienced some issues while setting up Slick 2.0.2. Any configuration that I do in one session is lost in the next. For example, in the first session, I create the table and add three people:
// H2 in-memory database
lazy val db = Database.forURL("jdbc:h2:mem:contacts", driver="org.h2.Driver")
// Contacts table
lazy val contacts = TableQuery[ContactsSchema]
// Initial session
db withSession { implicit session =>
contacts.ddl.create
// Inserts sample data
contacts += Person("John", "123 Main street", 29)
contacts += Person("Greg", "Neither here nor there", 40)
contacts += Person("Michael", "Continental U.S.", 34)
// Successfully retrieves data
contacts foreach { person =>
println(person)
}
}
All is well up to this point. The output repeats the three people whom I added. When I start a new session, I start to experience issues.
// New session in which the previous data is lost
db withSession { implicit session =>
contacts foreach { person =>
println(person)
}
}
The above block creates a org.h2.jdbc.JdbcSQLException: Table "CONTACTS" not found exception. If I edit as follows
db withSession { implicit session =>
contacts.ddl.create
contacts foreach { person =>
println(person)
}
}
then all the data is erased.
I see that the Scalatra guide to Slick uses a similar configuration to mine. What am I doing wrong? How should I get the data to persist between sessions? Does the fact that I am using an in-memory database have anything to do with it?
Two choices.
Either create a session and keep it open. That can be done with a withSession scope lower on the call stack or db.createSession.
Or add ;DB_CLOSE_DELAY=-1 to the database url. That keeps the db alive as long as the vm runs.
See http://www.h2database.com/html/features.html#in_memory_databases
I want to allow users to update their email, so I have controller :
[HttpPost]
public ActionResult ChangeEmail(string newEmail) {
IUser user = _services.WorkContext.CurrentUser;
if (!user.Is<UserPart>())
throw new InvalidCastException();
var userRecord = user.As<UserPart>().Record;
userRecord.Email = newEmail;
return null;
}
Everything builds and runs OK except that the database doesn't update new email.
What should I do ?
Thanks all !
I think your problem is that you are trying to update the Record directly instead of setting the value of the Part and letting Orchard save your changes:
user.As<UserPart>().Email = newEmail;
Your change will be automatically committed to the db at the end of the request.
As a side note the reason your changes are not saving is that when you update a record you need explicitly update it using an injected repository e.g. _userRepository.Update(user.Record) where _userRepository is an injected IRepository<UserPartRecord>, but just updating the part is the way to go.