I am trying to default sort an association, my domain classes are as follows
Class Section{
Integer displayOrder
static hasMany=[questionCategories:QuestionCategory]
static mapping={
questionCategories sort:'displayOrder'
}
}
Class QuestionCategory{
Integer displayOrder
static hasMany=[questions:Question]
static mapping={
questions sort:'displayOrder'
}
}
Class Question{
Integer displayOrder
}
basically i want to get a list of section objects which is sorted by section class's displayOrder, the inner questionCategories sorted by questionCatgory Class's displayOrder and similarly questions sorted by Question class's displayOrder
I have tried SortedSet approach and that works fine, but unfortunately we cannot use it
with this configuration i am getting this error
java.sql.SQLSyntaxErrorException: ORA-00904: "QUESTIONCA3_"."DISPLAY_ORDER": invalid identifier
This looks like your database is not setup correctly. One of your underlying tables doesn't have a "DISPLAY_ORDER" column. Judging by the "QUESTIONCA3_" I'd guess it's the table related to QuestionCategory.
Related
I've been searching for an answer on how to delete ALL records from a table using LINQ method syntax but all answers do it based on an attribute.
I want to delete every single record from the databse.
The table looks like so:
public class Inventory
{
public int InventoryId { get; set; }
public string InventoryName { get; set; }
}
I'm not looking to delete records based on a specific name or id.
I want to delete ALL recods.
LINQ method syntax isn't a must, bt I do prefer it since it's easier to read.
To delete all data from DB table I recommend to use SQL:
Trancate Table <tableName>
Linq is not meant to change the source. There are no LINQ methods to delete or update any element from your input.
The only method to change you input, is to select the (identifiers of the )data that you want to delete in some collection, and then delete the items one by one in a foreach. It might be that your interface with the source collection already has a DeleteRange, in that case you don't have to do the foreach.
Alas you didn't mention what your table was: Is it a System.Data.DataTable? Or maybe an Entity Framework DbSet<...>? Any other commonly used class that represents a Table?
If you table class is a System.Data.DataTable, or implements ICollection, it should have a method Clear.
If your tabls is an entity framework DbSet<...>, then it depends on your Provider (the database management system that you use) whether you can use `Clear'. Usually you need to do the following:
using (var dbContext = new MyDbContext(...))
{
List<...> itemsToDelete = dbContext.MyTable.Where(...).ToList();
dbContext.MyTable.RemoveRange(itemsToDelete);
dbContext.SaveChanges();
}
I am using ServiceStack.Ormlite, and also make heavy use of the automatic handling of enums whereby they are stored in the db as strings but retrieved and parsed nicely back into Enums on retrieval, so I can do easy type-comparison - say, for a property "UserRole" in the db/table class "User" of enum type "UserRoleEnum" (just for demonstration).
This works great.. until I want to use the enum property to define a multi-column unique constraint
CompositeIndexAttribute(bool unique, params string[] fieldNames);
like:
[CompositeIndex(true, nameof(UserId), nameof(UserRole)]
public class User
{
public long UserId {get;set;}
public UserRoleEnum UserRole {get;set;
}
(as per :
How to Create Unique Constraint with Multiple Columns using ServiceStack.OrmLite? ).
At which time i get:
System.Data.SqlClient.SqlException
Column 'UserRole' in table 'User' is of a type that is invalid for use as a key column in an index.
I currently see options as:
a) Define UserRole as a string (isntead of UserRoleEnum ) in the table entity class and lose the Enum use.... having to manually test the value each time to confirm that the db value is one that i expect in my business logic later
b) Continue to use UserRoleEnum but lose the ability to declare multicolumn uniqueconstraints using the class attribute, and probably have to create these manually using a subsequent db migration script?
Is there any way to make the enums and the multicolumn constraint play nicely, out of the box?
This issue was because enum properties were using the default string definition fallback of VARCHAR(MAX) which SQL Server doesn't let you create indexes on whereas the column definition of a string property is VARCHAR(8000).
This issue is now resolved from this commit which now uses the VARCHAR(255) string definition of the EnumConverter Type Converter. This change is available from v4.5.5 that's now available on MyGet.
Otherwise you can also change the size of the column definition to match a string property by adding a [StringLength] attribute, e.g:
[CompositeIndex(true, nameof(UserId), nameof(UserRole))]
public class User
{
public long UserId { get; set; }
[StringLength(8000)]
public string UserRole { get; set; }
}
I am new to Grails. I installed Grails 2.4.4 version and Spring Tool Suite.
I created Grails project and domain ,controller classes. But i am getting all the fields as mandatory by default and "id" is not generated. Need some help.
Domain Class:
package org.example.pomorodo
class Task {
String summary
String details
Date dateCreated
Date deadLine
Long timeSpent=0L
static constraints = {
}
}
Controller Class:
package org.example.pomorodo
class TaskController {
static scaffold =Task
}
Do you mean you can't access the "id" property after saving your domain object with GORM? Or just that the generated code doesn't have an "id" property explicitly defined? If it's the latter, don't worry. The "id" property is automatically injected by metaprogramming black-magic by the framework. If it's the former, something else is wrong, as you should definitely have a valid "id" after saving a domain object.
On the mandatory fields: Use the constraints block to toggle fields to nullable = true. Example:
package org.example.pomorodo
class Task {
String summary
String details
Date dateCreated
Date deadLine
Long timeSpent=0L
static constraints = {
summary(nullable:true)
details(nullable:true)
}
}
You can also modify default constraints globally. See the constraints documentation for more details.
Recently I got a query regarding mapping a database table which do not have any id and version. For example the table have two varchar fields username and password nothing more than that.
Although it was something strange for me that table doesn’t have the id field. The good thing is that the username is a primary key in the table and this is not auto incremented user want to create it by his own method.
The good thing about grails is, in most of the cases you get your answer in the docs http://grails.org/doc/latest/ . So in this case we just need to change the id field in grails domain like this
class Test {
String username
String password
static mapping = {
id name: 'username'
version false
id generator: 'assigned'
}
static constraints = {
username(nullable: true)
}
}
I have been using the WebAPI in ASP.Net to allow access to our Entity Framework Objects.
The problem I am having is converting the objects to a custom POCO for our end customers to use.
I need to convert the Entity Framework Object to a custom POCO.
For example in our SQL Database we have Tbl_Person with the following properties
PersonID
FirstName
SureName
DateOFBirth
AnnualSalary
This table maps to an Entity Framework class Person with the same properties.
But I want to change the properties so that when a end customer accesses it they get a POCO like:
PersonID
Name
Age
SalaryRange
I also want to keep the current features such as JSON & XMLoutput and allow for OData queries.
I have been trying to 'Collect' the Odata Query and applyto my database context but this does not seem to be work correctly
Please see code example below:
Imports System.Net
Imports System.Web.Http
Imports System.Data.Entity
Public Class PeopleData
Inherits DbContext
Public Property People() As DbSet(Of Person)
End Class
Public Class Person
Public Property PersonID() As Integer
Public Property FirstName() As String
Public Property SureName() As String
Public Property DateOFBirth() As Date
Public Property AnnualSalary() As Integer
End Class
Public Class PeopleController
Inherits System.Web.Http.ApiController
Private db As New PeopleData
Function GetPeople(query As OData.Query.ODataQueryOptions(Of Person)) As IQueryable(Of apiPerson)
Dim pep = query.ApplyTo(db.People)
Dim resPep As New List(Of apiPerson)
For Each p In pep
resPep.Add(New apiPerson(p))
Next
Return resPep.AsQueryable
End Function
End Class
Public Class apiPerson
Public Sub New(ByVal p As Person)
PersonID = p.PersonID
Name = p.FirstName & " " & p.SureName
Age = Date.Now.Year - p.DateOFBirth.Year
If p.AnnualSalary > 15000 Then
SalaryRange = "High"
Else
SalaryRange = "Low"
End If
End Sub
Public Property PersonID() As Integer
Public Property Name() As String
Public Property Age() As Integer
Public Property SalaryRange() As String
End Class
I have two problems:
1) The API help pages don't populate and only produce this error: 'Sample not available.'
I like the dynamic help pages & that they pick up code comments, this is a really quick and easy way to maintain documentation. How can I get them to work with the ApiPerson?
2) If I try /api/people?$filter=Age eq 29 I get an error Type 'MvcApiPeople.Person' does not have a property 'Age'.
I understand that the LINQ Query is been passed to the 'Person' and that property does not exist but how can I 'Translate' queries to map to different properties in the actual Database Object?
Your action declaration should be
Function GetPeople(query As OData.Query.ODataQueryOptions(Of apiPerson)) As IQueryable(Of apiPerson)
i.e query parameter should be of type ODataQueryOptions (Of apiPerson) not ODataQueryOptions (Of Person).
Regarding your question 1:
I think your problem is that the apiPerson-class is missing a parameterless constructor.
Also, I found a blog post with some information on how to customize sample generation when the default generation mechanism doesn't work:
http://blogs.msdn.com/b/yaohuang1/archive/2012/10/13/asp-net-web-api-help-page-part-2-providing-custom-samples-on-the-help-page.aspx.
After playing around with many different solutions I decided the simplest way to control the information that is made available on an API and still allow iQueryable is to control the data at database level or at class level with Data Contract annotations.
I actually created views in my database to render the data exactly how I want it to appear for end customers. I felt this had the best benefits for performance and speed of implementation.
Thank you to all the guys who offered suggestions.
I am trying to extend my Linq-to-Sql entity with a few extra properties. These are "calculated" properties based on data from the underlying SQL View. For example, think of having a Date of Birth field, which is used to calculate an extended Age field.
I tried to extend my entity class by extending the OnLoaded() method.
I get a compile time error however stating that I cannot create it. I checked the designer code for my LTS entity class, and it doesn't have a partial definition for any of the expected extension points.
I checked a few of my other LTS entity classes and they do have these extension points. The only difference I see is that the one without is loaded from a SQL View, rather than a table. Is there a way to hook into a "Loaded" event when loading from a SQL View?
TIA!
I found that I did not have a PrimaryKey specified for my Linq-to-Sql entity class. I believe without a Primary Key specified, no extension methods generated in the entity class. Once I specified a Primary Key on my LTS entity class definition (through the designer), I was able to extend the OnLoaded() event.
You can do this by means of a property. Just create a partial class with the same name as your entity. Any properties or methods that you add will automatically be part of the entity and allow to use any of its members.
Here's an example of the pattern:
public partial class [The Name of the Entity]
{
public int Age
{
get
{
return CalculateAge(this.DateOfBirth);
}
}
}
Here's some logic on how to calculate the Age (Source: Geekpedia)
public static int CalculateAge(DateTime BirthDate)
{
int YearsPassed = DateTime.Now.Year - BirthDate.Year;
// Are we before the birth date this year? If so subtract one year from the mix
if (DateTime.Now.Month < BirthDate.Month ||
(DateTime.Now.Month == BirthDate.Month && DateTime.Now.Day < BirthDate.Day))
{
YearsPassed--;
}
return YearsPassed;
}