How to avoid generating Default primary key id in Golang (beego) model? - api

I am trying to create a rest API. I have already a database. I want to create a struct linked to a database table. But when I run the project beego automatically creates an "id" primary key for the model registered. How to avoid this in beego?
My code example:
Model:
type Person struct {
PersonId string `json:"person_id"`
name string `json:"name"`
email string `json:"email"`
}
Problem: Encounter need a primary key field when using beego
It creates an id field in db table with default null value.
Note: person_id is the primary key in person table.

If you want Beego’s ORM to have a different primary key, you should use this:
type Person struct {
PersonId int64 `orm:"pk" json:"person_id"`
name string `json:"name"`
email string `json:"email"`
}
You can check the official documentation here in the primary key section:
Beego Model Definition
This might be happening because when creating your table you have primary_key set to auto. Which is the default Beego behaviour.
Please check this article also:
https://developpaper.com/question/beegos-orm-gives-the-primary-key-value-every-update-delete-read/

Related

Renaming a table and a foreign key fails using ef6

I use EF6 and code first migrations. I have a two tables
public class Team {
public int Id { get; set; }
public string Name { get; set; }
}
public class TeamMember {
public int Id { get; set; }
public string Name { get; set; }
public Team Team { get; set; }
public int TeamId { get; set; }
}
I want to rename TeamMember to TeamMemberDeprecated and add a new tabled named TeamMember with some differences to the table layout. The main reason I am creating a new table is data. I want to save all of the data in the current TeamMember table so I need to rename it, and I want to transfer only the specific data I need to the new TeamMember table.
When I add the migration it looks like this
RenameTable(name: "dbo.TeamMember", newName: "TeamMemberDeprecated");
What it doesn't do is change the name of the foreign key property from FK_dbo.TeamMember_dbo.Team_TeamId to FK_dbo.TeamMemberDeprecated_dbo.Team_TeamId.
This presents a problem when I go to create the new TeamMember table because the foreign key FK_dbo.TeamMember_dbo.Team_TeamId already exists in the database.
I tried dropping the foreign key and renaming it, but this doesn't do anything and when I run the migration -verbose I see why it's expecting the foreign key to be null. I want to keep the data, but perhaps my approach is wrong.
Any suggestions are welcome, thanks.
Let EF rename the table, then go to SQL management studio and manually rename the foreign keys.
Go back to EF, make the changes, run the migration and let EF create the new foreign keys
Don't forget to backup your DB
In EF Core 5.?? there should be a few new commands (see EFCore GitHub Pull):
RenamePrimaryKey
RenameUniqueConstraint
RenameForeignKey
However, it seems that these will drop and recreate the key/constraint. In MSSQL this is not only unnecessary, but very costly. When the constraint is reapplied the database much check that each item is unique or present in the foreign table. If you can help it, do not do this.
Instead I recommend the below. You must specify the schema in the first parameter for the new name, but not in the second. The square brackets will help if any lunatic has put dots in table or constraint names:
migrationBuilder.Sql("sp_rename '[dbo].[PK_TeamMemberDeprecated]', '[PK_TeamMember]'");
It works the same for foreign keys:
migrationBuilder.Sql("sp_rename '[dbo].[FK_TeamMemberDeprecated_TeamID]', '[FK_TeamMember_TeamID]'");

GORM One-to-Many relationship without foreign keys

I've been trying for a while to understand how GORM works, and I think I've got it down. However, I'm having a heck of a time getting my relationships correct.
Here is my database schema setup (2 tables):
Table - Users
userhash varchar(255)
firstname varchar(255)
lastname varchar(255)
Table - Logs
userhash varchar(255)
accessdate date
There are no foreign key and primary key constraints defined in the tables. However, in the users table the userhash will be unique. I didn't design it this way, but I have to use it like this.
Now for my Grails domain classes:
Class - Users
class Users {
String userhash;
String firstname;
String lastname;
static hasMany = [logs: Logs]
}
Class - Logs
class Logs {
String userhash;
Date accessdate;
static belongsTo = Users;
}
In my controller, I do the following:
def user = Users.findByUserhash("nraboy");
println user.firstname;
println user.logs;
It prints out the correct firstname, but when I try to display the logs, it is null or empty. Am I requesting the data incorrectly for child tables or am I missing something somewhere in the domain class design?
I've tried to do the following, but had now luck as well:
Class - Logs
static mapping = {
id generator: "assigned", name: "userhash", type: "string"
}
Class - Users
static mapping = {
userhash generator: "foreign"
}
I figured the above would let me manually define the primary key and foreign key via code since it didn't exist int he tables. No luck though.
Any help would be appreciated.
Thanks,
It looks like you may have to do something with in Users for the logs association to force the foreign key to be in the Logs table, as it is. See the GORM docs One-to-Many Mapping section. Perhaps something like:
static hasMany = [logs: Logs]
static mapping = {
logs column: 'userhash'
}
I would be curious to hear if this worked...

EF Table with multiple references to same Table

I have a Database First Entity Framework Model
Tables:
1) User
Id
2) Article:
Id
UserCreated > Ref to User last edited User
UserChanged > Ref to User which created the Article
Enity Framework is Generating a Model like this
Partial Public Class Article
Public Property ID As Integer
Public Property UserCreated As Integer
Public Property UserChanged As Integer
Public Overridable Property User As User
Public Overridable Property User1 As User
End Class
Now I have another table like Vouchers also with UserCreated and UserChanged but names User1 and User.
Is there any way to specific the name of the property without changing the class itself because its generated from the Database.
You can use a DataAnnotation on the UserCreated property to specify the foreign key name:
[ForeignKey("UserCreated")]
http://msdn.microsoft.com/en-gb/data/gg193958.aspx
You can easily change the property name for User1 to any other name using the edmx-Designer.
But you should be aware that User is the reference to the column UserCreated. Because it may be that User references to UserChanged. You should check that. The best way is to check the name of the relationship. Therefore you need to give the relationship a meaningful name that you are able to distinguish them. Then you can right click on the relationship line and retrieve the relationship name.

Grails; how to refer to a domain property in native sql query

I have a domain class UserProfile which has one to one relationship with another domain class User.The Structure of the domain is provided.
сlass UserProfile {
String fio
String position
String phone
String email
static belongsTo = [user: User]
static constraints = {
// some constraints
}
static mapping = {
//some mapping; user property is not mapped
}
I need to write a native sql query in Grails for UserProfile domain and I don't know how to refer to user property(static belongsTo = [user: User]). I have tried USER_ID but it is not working.
I can't name the column directly using mapping section; I just need to find out how user column in UserProfile domain is named in database and how it can be called in native sql query.
Very Simple if i got your question ,Grails gorm convention for storing fileds in data base is:
Like
user_profile for UserProfile -Domain
and all fileds are speparedted by underscores and most of the time gorm adds _id after a foreign key reference /or a GORM relationship like above One to One and one to Many
[belongsTo=[user]] .
Inside SQL Table
mysql describe user_profile ;
----------------------------------------------------------------
User_Profile
----------------------------------------------------------------
id
version
foo varchar(50)
postion
email
user_instance_id int
-------------------------------------------------------------------
NATIVE SQL QUERY WILL BE :
'select up.user_instance_id from user_profile as up '
the Get all the userInstance objects by querying the user table
'select * from user where user.id = 'the id you get it from the above query'
I hope you have some idea on this please ,if i didnt get it let me know.
I believe if you define user inside UserProfile, then you can access it and will automatically be mapped? It works in my previous projects, I hope it will work with this.
сlass UserProfile {
String fio
String position
String phone
String email
static belongsTo = [user: User]
User userInstance;
static constraints = {
// some constraints
}
Then you can use it
UserProfile.executeQuery("select up.userInstance from UserProfile up")

Fluent NHibernate Mapping Single Column to Composite Key

I have a situation where i have defined an entity in my domain model in which I would like to expose a single id column.
public class OfferedProduct
{
public virtual string Id {get; set;}
//other properties
}
The legacy database table this will map to is
CREATE TABLE ProductGrouping
MemberNumber INT NOT NULL,
GroupId CHAR NOT NULL,
...
I dont want to compromise the domain model by introducing two properties and mapping them using the "CompositeId" construct.
CompositeId().KeyProperty(x => x.MemberNumber).KeyProperty(x => x.GroupId)
What I want ideally is to concatenate the two values in the form {MemberNumber}{GroupId} and expose this as the Id value. I would then use a Custom Type to handle how these values are concatenated when retrieved from the DB and broken apart when saving/selecting.
I have noticed that the "CompositeId" method does not allow a customType as with the standard "Id" call; but the "Id" method does not provide the ability to set multiple columns. I have seen examples where people have used "Map" to combine two columns using a custom type, but not for id values.
I have noticed the "CompositeId" has an overload that can take a custom identity class but I am unsure how to use it in this scenario.
CompositeId<OfferedProductIdentifier>(x => x.?)
Any help would be greatly appreciated.
in case someone comes here
CompositeId()
.KeyProperty(t => t.Id, c =>
c.Type(typeof(MyUserType)).ColumnName("MemberNumber").ColumnName("GroupId"));