Adding data to Postgres database with Entity Framework Core HttpPost failing because of child table constraint - postgresql

I am trying to add some data to a Postgres database using Entity Framework Core via a Http POST method.
The data to be added is passed in the body of my post request which looks like this:
{"id":42,"name":"Hans Musterman","email":"hans#gpost.com", "gender": {"id": 2, "name": "male"}}
Which is exactly the structure I would get returned using a get request.
Still the insert fails with an error:
Duplicate key value violates unique constraint "PK_Genders"
Of course the gender male already exists in the Genders table. What I want to do is add a user to the users table with a gender but referenced for the new user but not new created. What the system seems to do when using DbContext Add is trying to add User and Gender.
Is there a way to do it with a reference? Adding a User with "gender" = null does work.

I think you should have something like genderId or foreign key that reference the gender table in the user model use that foreign key id (genderId) instead of gender.
eg. in you user object
{ ... "genderId": 2 }
Otherwise Entity Framework is going to create a new gender that is why you are getting that error

Related

Fiware Orion-LD Auto Increment Entity Id

An Entity Id is required for each new entity in the broker.
In NGSI-LD the format for the Entity Id is urn:ngsi-ld:TemperatureSensor:001.
Is it possible to somehow autoincrement the number of the Entity so that the new Entity can be created programmatically?
For example, provide something like urn:ngsi-ld:TemperatureSensor:* and the new Entity can be created with an auto-incremented Entity Id.
Thanks.
The id should be generated by the application itself. You have multiple ways of generating unique ids but I would recommend ids that have some semantics behind so that you can, for instance, infer from an id in which area the sensor is located, who the owner is, etc.

Sails- relationship mapping

I've 2 sails model
1) student
id - pk
name
revision
2) studentDetails
id
student_id -> fk
student_reviosion
Whenever student gets updated, revision is automatically increment by 1. How I can make sure that revision and student_revision should be sync in both table? Is there any way to define sails_model like that?
I know this can be achieve through lifecycble callback and would like to know if anything that we can directly achieve by defining some relation in sails models itself.
You should choose just one of these tables to store the data in. Since you are creating a relation, you will be able to access the data when you need it. For example if you keep revision in student, when you look up student details, you can do something like let studentDetails = await StudentDetails.find({id: id}).populate('student') [I am naming the foreign key to 'student' because it will make more sense when you populate it like this].
Then you can access all the information from the associated student record, like studentDetails.student.revision
https://sailsjs.com/documentation/concepts/models-and-orm/associations/one-to-one

Entity Framework 6 - Form relationship using object which doesn't exist in the DB yet

Suppose a Company has Employees. Company 'Solutions' has Employee 'James'.
These entities are both saved in the DB, and their relationship is expressed through a foreign key.
At the application level, the Employee class has a Company object property, to define the relationship.
Suppose a new company 'Better Solutions' is created, which doesn't exist in the DB yet, and James now moves to this company.
How do I tell EF to handle this? Currently I:
Save the new company 'Better Solutions' (object created with a GUID ID) to the DB:
db.Companies.Add(newCompany);
Change the Company property on Jame's instance:
james.Company = newCompany;
Tell EF that a property on James's instance has changed and needs updating:
db.Employees.Attach(james);
db.Entry(james).State = System.Data.Entity.EntityState.Modified;
But when this happens, the newCompany object doesn't have its new database ID yet (even though it's been added to the database, the object still holds the GUID ID), so when saving EF tries to do this:
UPDATE [dbo].[Employee]
SET [CompanyID] = SomeGUID,
WHERE ([EmployeeID] = JamesID)
Which of course throws an exception because no CompanyID matches that GUID:
The UPDATE statement conflicted with the FOREIGN KEY constraint
In this scenario, do I need to first push the newCompany object to the DB, then retrieve it from the DB (to get the new ID), then set this retrieved object as James's Company property?
Or does EF have a cleaner way of taking care of all this?
try to do like below. Save company first then assign it to james that will update existing employee.
db.Companies.Add(newCompany);
db.SaveChanges();
james.Company = newCompany;
db.SaveChanges();

How to retrieve object from database to put as foreign key

In my database, I have table "User" and "Role" and I search to put a role in a user when the user sign up. The problem is that when I retrieve the role from database and post the user, a new role is create and I don't want it. I want the a existing role are put as foreign key.
In JPA you don't think as foreign keys. What you model is an Object which can have relations to other objects, such as a class User may have a list of Role references.
You'd then annotate it with the according JPA annotations to map this relation to your database tables. You may check the Oracle Java EE tutorial on JPA to learn how to do that.
Then, when putting a new Object (meaning one with a new ID) into the list, it will result in getting a new entry in the referring table when persisting it.

Query to database with 'primary key' on GoogleAppEngine?

I've made a guestbook application using Google App Engine(GAE):python and the client is running on iPhone.
It has ability to write messages on the board with nickname.
The entity has 3 fileds:
nickname
date
message
And I'm about to make another feature that user can post reply(or comment) on a message.
But to do this, I think there should a 'primary key' to the guestbook entity, so I can put some information about the reply on a message.
With that three fields, I can't get just one message out of database.
I'm a newbie to database. Does database save some kind of index automatically? or is it has to be done by user?
And if it's done automatically by database itself(or not), how can I get just one entity with the key??
And I want to get some advise about how to make reply feature generally also. Thanks to read.
Every entity has a key. If you don't assign a key_name when you create the entity, part of the key is an automatically-assigned numeric ID. Properties other than long text fields are automatically indexed unless you specify otherwise.
To get an entity if you know the key, you simply do db.get(key). For the replies, you probably want to use a db.ReferenceProperty in the reply entity to point to the parent message; this will automatically create a backreference query in the message to get replies.
Each entity has a key, it contains information such as the kind of entity it is, it's namespace, parent entities, and the most importantly a unique identifier (optionally user specifiable).
You can get the key of an entity using the key method that all entities have.
message.key()
A key can be converted to and from a URL-safe string.
message_key = str(message.key())
message = Message.get(message_key)
If the key has a user-specified unique identifier (key name), you can access it like this
message.key().name()
Alternatively, if a key name was not specified, an id will be automatically assigned.
message.key().id()
To assign a key name to an entity, you must specify it when creating the entity, you are not able to add/remove or change the key name afterwards.
message = Message(key_name='someusefulstring', content='etc')
message.put()
You will then be able to fetch the message from the datastore using the key name
message = Message.get_by_key_name('someusefulstring')
Use the db.ReferenceProperty to store a reference to another entity (can be of any kind)
It's a good idea to use key name whenever possible, as fetching from the datastore is much faster using them, as it doesn't involve querying.