How can I Alias Data in a WebGrid - asp.net-mvc

I have an existing database that I can't change. I have a column of type int that has various numbers that mean something.
This something would be a string. For example, 1="dog", 2="cat", 3="bird". There are a dozen or so integers to deal with.
I'm using ASP.NET MVC 3 with EF 4.1 and have a WebGrid binding to the Model. Is there a way to alias the data for these integers listed in the WebGrid to display the string value that mean something to the user?
Any help on this would be greatly appreciated!

Add an enum to your Model:
public enum foo
{
dog = 1, cat, bird //etc
}
Hopefully, you are using ViewModels. If you are, add a property for the enum:
public foo thing {get;set;}
And set the value of thing based on the integer value you get from the database:
Model m = new Model{number = 3};
m.thing = (foo) m.number;
Or you could create a helper and use that within the format parameter to set a value based on the integer, or you could use JavaScript/jQuery to alter the values from ints to strings once they have been rendered to the browser.

Related

In MVC, how can I retrieve records from database matching a range of string serial numbers that include numbers?

I have an MVC application that uses Code First Entity Framework.
I have records in my database for serial numbers that are strings, and a combination of letters and numbers. The last 4 are always the number part.
I am trying to retrieve all records in between range A and B, so for example from SERIAL-NO-0020 to SERIAL-NO-0050
I cannot convert the string number part to an integer because Linq To Entities doesn't support it. So as an example to get all records with a serial number higher than 20, this doesn't work:
var records = context.SerialNumbers.Where(m => Convert.ToDecimal(m.SerialNo.Substring(10, 4)) > 20).ToList();
Is there a way to do this without first pulling all the records from the database and filtering further?
Convert.ToDecimal can't be translated to SQL when using it with Linq to Entities.
You can create a stored procedure that query the data so you can do anyahting that can't be done by EF.
Another solution is to create a computed column.
First, add a new property. Let name it SerialId in your SerialNumber entity.
Second, Decorate that property with a data annotation:
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
or use fluent configuration if you want:
modelBuilder.Entity<SerialNumber>().Property(t => t.SerialId)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Computed);
Third, Add new EF migration and in the generated migration file, just update it by passing a new value to defaultValueSql parameter liek below:
public override void Up()
{
AddColumn(
"dbo.SerialNumber",
"SerialId",
c => c.Int(nullable: false, defaultValueSql: "CAST(SUBSTRING(SerialNo, 11, 4) AS INT)"));
}
The modification says that each line of SerialNumber table has a generated column and its value is calculated by using this SQL statement => CAST(SUBSTRING(SerialNo, 11, 4) AS INT)
You can update your database by running ef command => update-databse.
Finally, you can change your Linq to Entities like below and you don't need any conversion:
var records = context.SerialNumbers.Where(m => m.SerialId > 20).ToList();
Instead of Writing Queries you can write SP and access this SP (Stored Proceure) with the help of Linq.
In SP you can split the record first and then compare. It will also take less time and increase the performance.

How do I create a Grails query for a many-to-many using primitives?

I have a POGO we'll call Foo and it has a list of Bars. In the database, these are simple integers, but they're stored in a separate table (Foo_Bars)
class Foo {
String name
...
static hasMany = [bars:Integer]
...
}
So my question is, how do I create a query to find all Foos that with bars that are in a list. I know how I would write it in SQL.
SELECT * FROM foo, foo_bars
WHERE foo.id = foo_bars.foo_id
AND foo_bars.bars_integer IN (11, 15, 52)
But I figure there must be a simpler way, using GORM or HQL. How would I write this?
but what exactly you want to achieve? list of Foo's where bars is equal to (11,15,52), or ONE OF bars is in the list or the list of bars contain each of given list?
either way, I doubt you can do it in criteria or using a dynamic finder, I'm trying to do it in an unit test and nothing worked
I would go with creating another domain class like
class FooBar {
Foo foo
Integer integer
}
which would create exactly the same database table as you already have, and then querying would be much simpler

Rails 4.1 enum query

I am seeing Rails generate the wrong query value when I use an enum col value in a where clause, like this (self added for clarity). dominant_product_strategy is an enum.
def some_model_method_on_myModel
MyModel.where(dominant_product_strategy: self.dominant_product_strategy)
end
This produces the correct value (again, self just added for clarity):
MyModel.where(dominant_product_strategy: self.attributes["dominant_product_strategy"])
I'm guessing that Rails sees the enum as a string, and then converts to a integer value of zero. Ughhhhh!
Am I missing something?
This also works:
MyModelwhere(dominant_product_strategy: MyModel.dominant_product_strategies[dominant_product_strategy])
It seems to be that you have answered your question by yoursef. Enum variables is a hash:
{str1: int1, str2: int2, ...}
The value (integer) is storing in DB, and the string is just representation of the int value. When you call self.dominant_product_strategy, you get the representation (string) of dominant_product_strategy column storing as integer in DB.
I think that your first working solution (self.attributes["dominant_product_strategy"]) is fine.

Sorting Datatable with linq with correct datatype of a column

hello I have this code that use to sort a datatable.
Dim sortingIndex As Integer = orderby
Dim DataTableNew As DataTable = New DataTable
DataTableNew = dt.Clone
Dim query = (From c In dt.AsEnumerable Order By c.Field(Of String)(sortingIndex) Ascending)
query.CopyToDataTable(DataTableNew, LoadOption.OverwriteChanges)
My problem is that with this method I always need (Of String) for it to work, so the date columns are also managed as Strings witch is the problem. Is there a way to use the correct type so the sorting is based on the type of the column?
Linq rocks, but sometimes the good old methods are better. You can do
dt.Select(string.Empty,dt.Columns[sortingIndex].ColumnName)
It sorts the DataTable using the column's data type.

Cast Varchar as Integer in propel for addAscendingOrderByColumn

I have a method in order to get data out of a database for a propel-based symfony-1.1 project.
Now the use-case arrived to store an integer into a varchar field, which results in a wrong order, e.g. {1, 17, 5}, and not the numeric one I was expecting, i.e. {1, 5, 17}.
I know that one way would be to redesign my schema.yml, but this is not an option. I was wondering if there is a way to cast said varchar field as an integer without harming the propel-approach.
This is the sorting function:
public static function getFooData($column = 'FooPeer::ID', $orderBy = 'asc') {
//FIXME: Sort varchar fields as integer, needed for FooPeer::REQUESTS
$c = new Criteria();
if ($orderBy == 'asc') {
$c->addAscendingOrderByColumn($column);
} else {
$c->addDescendingOrderByColumn($column);
}
return FooPeer::doSelect($c);
}
What about:
$c->addAscendingOrderByColumn('CAST('.$column.' AS UNSIGNED)');
Just for interest, you could also have written a view for this, and build your model on top of the view rather than the table. Assuming you're writing to the table with Propel, this solution requires the platform to support writable views (I'm not sure they all do, but perhaps that assumption is out of date).
This is often a good/quick technique where you're not sure how to do something in Propel, or where it is really awkward. It's saved me a few times, even though it's not every purist's cup of tea.

Resources