grails: primary key from view - grails

I have a requirement to create Employee and Role domain with ids which should be inserted at the time of creation and not manually inserted via code.
Following is attached code for Role.groovy
package pocgrails1
class Role{
String roleId
String roleName
static hasMany = [RoleACL]
static mapping = {id generator: 'assigned',name:"roleId",type:'string'}
static constraints = {
roleName blank:false
roleId blank:false
}
String toString(){
return id
}
}
I am having issues while generating the primary key from the view.
By default the scaffold does not generates the field to insert the primary key value.
I already have looked into several blogs and posts but none were of much help.
What should be the correct approach for this.
Many thanks in advance.
Rohit

Hard to understand what do you want to do. If you want to change primary id key define it as String id and change mapping:
class Role{
String id
static mapping = {
id column: 'role_id', generator: 'assigned'
}
}
When you save object an id will be generated for you and persisted to database, no need to create anything manually

Related

Set a Primary Key for an Entity without ingaffect database

I'm working on an ASP.NET MVC project, I use Entity Framework (Database First), I created a data model depend on SQL server database, I created a Table in the database and I updated the data model from the database, and when I try to add a record to the new table I created (this table doesn't have a PK) I got an error, when I search about the error I Understood that in Entity Framework need to have a PK for Entity.
So I ASK if I can set a Primary Key for an Entity without affect database, or any other solution to solve this problem.
You can use partial Class for set Key and without effect Original Model and Database
// orginal class **Entity** `YourEntity.cs`
public class YourEntity
{
public int Id { get; set; }
}
Then create a new Class must name different ordinal class ex YourEntityMeta.cs it is physical name
// must change name ordinal class `YourEntity.cs` but add **partial** keyword
[MetadataType(typeof(Metadata))]
public partial class YourEntity
{
sealed class Metadata
{
[Key]
public int Id { get; set; }
}
}
Entity Framework always needs a primary key column with name id. Add a column (id) in the database table and set "Is Identity: true" for it. Then update the database model of your project.

How to map table without primary key Entity Framework

I'm using Entity Framework to map some tables, but I can't do this unless I declare some column as the primary key.
The problem here is that my table in my database don't have a primary key and has millions of rows. I don't have permission to create a new Id column.
[Table("MYTABLE")]
public class myTable
{
[Column("NUMX")]
public virtual string NumX { get; set; }
[Column("NAME")]
public virtual string Name { get; set; }
[Column("AGE")]
public virtual int AGE { get; set; }
}
Obs: If I add the [Key] attribute to some column like Age, it works, but returns the wrong data.
Is there some way to omit the primary key?
I Figured out the problem.
Composite Keys works for me:
eg:
In my Context I defined some keys, not only one, but three keys:
public class MyContext : DbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
**//Here is the secret**
modelBuilder.Entity<MyModel>().HasKey(x => new { x.NumX, x.Name,x.Age});
}
}
Entity Framework requires a primary key unlike SQL.
EF use the primary key to uniquely identify rows (for example when you use .Find() or to perform update operations).
Infact not having a primary key remember a SQL VIEW, where you can only read data.
If any of the columns uniquely identify a certain row set it as a primary key (it can't be NULL) also if in Sql it isn't a key.
Otherwise if the combination of the columns are uniquely, create a composite key with these columns.
Remember that you should have a primary key in the 99% of cases, when you don't have a primary key you should stop and think if it make sense.

How to include only a single property when using 'expand'

I have an orders table which I want to query. One of the properties is "UserId" and which turns into a navigation property to the User.
I can query this to get the order and the associated User. However, I don't want the entire User entity, only the UserName property.
How do I construct that query in breeze?
Something like:
let query = new breeze.EntityQuery()
.from("orders")
.expand("user.userName");
I tried this, but then returned objects are not actually entities, but it does return just the userName:
let query = new breeze.EntityQuery()
.from("cases")
.select("field1, field2, user.userName");
Is there any other way of doing this? Note that I am using EF on the backside.
The best solution I found for this is creating a "virtual entity" which consists of just the two fields that I want. In other words, I have AspNetUsers as one table with it's corresponding entity. And then I have a second code first entity which consists of only the Id, and the UserName:
[Table("AspNetUsers")]
public partial class User
{
[Key]
[Column("Id")]
public string AspNetUserId { get; set; }
[StringLength(256)]
public string UserName { get; set; }
}
I can then use it as a relation in other tables and include it like was just another table.

legacy tables: none-id field named id

I am using a legacy database which has a field "usernr" as the primary key and a field "id" holding the user name. I added a mapping to get the usernr setup as the identifying property:
class User {
Long usernr
String id
String password
static mapping = {
id name: 'usernr', generator: 'sequence', params: [sequence: 'usernr']
}
}
But a scaffolding controller is not showing the id field itself. Since "id" seems to be a reserved keyword for mapping, I'm not sure if there is any way to get this setup correctly. Any suggestions?

Grails domain ID column validation issue

I have a simple domain object
class MyDomain
{
String id
String name
static constraints =
{
id unique:true
name nullable:true
}
static mapping =
{
table 'schema.MyDomain'
id column:'MY_ID', type:'string', generator:'assigned'
}
}
The issue I am having is when I call validate on the object, it returns true even when the id field is null. I had thought that all columns were nullable:false unless explicitly stated otherwise. If I change the line
id unique:true
to
id unique:true, nullable:false
then it seems to work fine. My main question is, why do I have to explicitly set nullable for the ID column? It is just a small line of code, but I don't like just adding in the tag of code without understanding why in case it is a symptom of a bigger problem.
The id column is auto generated and auto populated(when versioning is turned on[true by default]) and you shouldn't have to declare a new one.
This default id column is nullable:false by default and you can still set the mapping properties and id generation strategies like you have done above against it.
However if you want to define the default constraints for all domain in you app, you can do it globally by setting thwe following in your config.groovy file.
grails.gorm.default.constraints = {
myShared(nullable:true, size:1..20)
}
For more on constraints see the Grails documentation.

Resources