Linq-to-Sqlite : Unable to map a TEXT type sqlite column against a System.Double type of model property? - linq

I have a Sqlite database table named Movie whose columns basically store data simply in TEXT or INTEGER type (of course, Sqlite basically stores everything as just string the columns only have an affinity towards the type, if i am not wrong).
I am using Linq-to-Sqlite ORM to query my table data against a model named Movie. Below is the DDL for the table and code for the class.
CREATE TABLE Movie
(
Id integer NOT NULL PRIMARY KEY AUTOINCREMENT,
Title Text,
Rating TEXT,
IsSubtitle INTEGER
)
public class Movie
{
public int Id { get; set; }
public string Title { get; set; }
public double Rating { get; set; }
public bool IsSubtitle { get; set; }
}
Now when I try to fetch the movie records from the database using the ORM, it throws an exception :
System.InvalidOperationException was caught
HResult=-2146233079
Message=The 'Rating' property on 'Movie' could not be set to a 'System.String' value. You must set this property to a non-null value of type 'System.Double'.
Source=EntityFramework
StackTrace:
at System.Data.Entity.Core.Common.Internal.Materialization.Shaper.ErrorHandlingValueReader`1.GetValue(DbDataReader reader, Int32 ordinal)
at System.Data.Entity.Core.Common.Internal.Materialization.Shaper.GetPropertyValueWithErrorHandling[TProperty](Int32 ordinal, String propertyName, String typeName)
at lambda_method(Closure , Shaper )
at System.Data.Entity.Core.Common.Internal.Materialization.Shaper.HandleEntityAppendOnly[TEntity](Func`2 constructEntityDelegate, EntityKey entityKey, EntitySet entitySet)
at lambda_method(Closure , Shaper )
at System.Data.Entity.Core.Common.Internal.Materialization.Coordinator`1.ReadNextElement(Shaper shaper)
at System.Data.Entity.Core.Common.Internal.Materialization.Shaper`1.SimpleEnumerator.MoveNext()
at System.Data.Entity.Internal.LazyEnumerator`1.MoveNext()
at LinqToSqliteDemoApp.Program.Main(String[] args) in e:\Projects\TestApplications\LinqToSqliteDemoApp\LinqToSqliteDemoApp\Program.cs:line 25
InnerException:
Obviously, it cannot cast the TEXT type of data from the Rating column into the double data type of Movie class.
So I would like to know, is there any workaround to tell the ORM to implicitly map or convert the Rating column data to double data type while retrieving from the database ?

You need to read the docs on sqlite data types http://www.sqlite.org/datatype3.html, so use double in your create table statement

Related

Xamarin Forms, Grouping Realm

I am using Xamarin forms (.NET Standard project), Realm & MVVM Light and I need to group a list of objects based on the Initial of the last name so that I can display a jumplist within a listview.
I am having a problem when trying to group a RealmObject. I have a model like so...
public class Participant : RealmObject
{
public string FirstName {get; set;}
public string LastName {get; set;}
public string Email {get; set;}
public string RegistrationCode {get; set;}
//More properties skipped out for brevity
}
Based on this link, I also have a Grouping class like so...
public class Grouping<K, T> : ObservableCollection<T>
{
public K Key { get; private set; }
public Grouping(K key, IEnumerable<T> items)
{
Key = key;
foreach (var item in items)
this.Items.Add(item);
}
}
In my viewmodel, I am able to fetch the Participants (i.e IQueryable<Participant>) like so....
var participants = RealmInstance.All<Participant>();
I would now like to be able to group this by Initials of the last name for which I do the following:
var groupedParticipants = from participant in participants
group participant by participant.LastName.Substring(0, 1) into pGroup
orderby pGroup.Key
select new Grouping<string, Participant>(pGroup.Key, pGroup);
which throws the below exception:
System.TypeInitializationException: The type initializer for 'Realms.RealmCollectionBase' threw an exception. ---> System.ArgumentException: The property type IGrouping cannot be expressed as a Realm schema type
I have looked around but unable to find working examples of grouping Realm sets. Any help would be greatly appreciated.
Realm does not support Linq's GroupBy (or Select-based projections).
A workaround would be to take a Realm-based sorted query to a standard List and then perform your Linq GroupBy.
Example (using James Montemagno's Monkey project):
var realmSort = r.All<Monkey>().OrderBy(m => m.Name).ToList();
var sorted = from monkey in realmSort
orderby monkey.Name
group monkey by monkey.NameSort into monkeyGroup
select new Grouping<string, Monkey>(monkeyGroup.Key, monkeyGroup);

SQLite-net-pcl - Always returning ID as 0 (Xamarin)

I recently moved across from SQLite.NET to SQLite-net-pcl due to the Android 7.0 SQlite issue.
In the process I have updated all my libraries and all is working well with regards to insert/drop etc.
The only issue I have is that every time I retrieve an item from the DB it always has an ID of 0. This is causing problems with updating items. Has anyone had this issue before?
[SQLite.PrimaryKey, SQLite.AutoIncrement]
public int ID { get; set; }
public string objectId { get; set; }
public DateTime createdAt { get; set; }
public DateTime updatedAt { get; set; }
public string Title { get; set; }
Thanks in advance.
Please try using this, this worked for me
using SQLite.Net.Attributes;
[PrimaryKey, AutoIncrement]
public int? Id { get; set; }
Had almost the same situation.
with all rows returning id of 0
class ToDo : Java.Lang.Object
{
[PrimaryKey, AutoIncrement]
public int ID { get; }
except I simply had forgotten to type set; in the property.
one thing that might help someone with this sorta problem is using the
GetMapping() method to get some info on the mapping used when CreateTable() is used to create the table.
as example:
Toast.MakeText(this, db.GetMapping<ToDo>().TableName.ToString(), ToastLength.Long).Show();
Toast.MakeText(this, db.GetMapping<ToDo>().HasAutoIncPK.ToString(), ToastLength.Long).Show();
using this I found out that AutoIncrement (HasAutoIncPK = false) wasn't being set on my table.
See if you created the table with the methods CreateComand(query) and ExecuteNonQuery(). If this is the case, create your table with the CreateTable<Type>() method. The primary key and autoincrement attributes are initialized at the time of creating the table through said method
I have been struggling with the same issue here.
I was manually creating the tables to guarantee a smoother update process moving forwards rather than using the CreateTable methods available.
The fix that I eventually stumbled upon was that I was using the wrong data type for my PRIMARY KEY column.
Wrong definition
[RecordIndexId] int PRIMARY KEY NOT NULL
Correct definition
[RecordIndexId] integer PRIMARY KEY NOT NULL
To add a little context there is a big different between the int and integer data types. Explained in this SO answer
My problem was that I had an internal set for my ID property setter. This had to be public to work correctly.
I'd add this as a comment but alas... I don't have enough rep.

Entity Framework 4.2 One to many relationship

I have 2 tables in an existing database:
Table1
[Key] public int Id {get; set;}
public int CustomerID {get; set;}
List<Table2> Table2Items {get; set;}
....
Table2
[Key] public int Id {get; set;}
public int customerid {get; set;}
Table1 Table1Item {get; set;}
...
I want to create a one-to-many relationship, such that each record in table1 can have many associated records in table2.
Its normally straight forward using the primary key field in table1 which matches the foreign key field (customerid) in table 2.
But I want to relate the 2 tables based on the CustomerID in table1 with the customerid in table2.
The following appears to relate the 2 tables by using the customerid field in table2 with the primary key in table1, which is not what I require.
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Table1>()
.HasMany<Table2>(s => s.Table2Items)
.WithRequired(s => s.Table1Item)
.HasForeignKey(s => s.customerid);
}
How can I modify the code shown above to fit my requirements.
What you are trying to achieve is impossible with current version of Entity Framework. Quoting from https://stackoverflow.com/a/7022799/337294:
It is not possible. Relations in EF follows exactly same rules as in the database. It means that principal table must have unique identifier which is referenced by dependent table. In case of database the identifier can be either primary key or unique column(s) of principal table. Otherwise it is not valid relation.
And since Entity Framework does not support unique indexes yet (despite strong demand in their Feature Suggestion page), it has to be the Id property of your Table1 class.

SimpleData casting objects with ALL_CAPS and underscores

I'm not sure if anyone else has run into this, but I am having a heck of a problem when trying to cast returns from an Oracle database that has column names in ALL_CAPS with underscores. I am trying to figure out a code way to get it done, but it looks like the cast calls aren't homogenizing. Here is a quick example:
MY_TABLE { COLUMN, COLUMN_ONE, COLUMN_TWO } = {{"a", "b", "c"}}
When mapping to
public class MyClass
{
public string Column { get; set; }
public string Column1 { get; set; }
public string Column2 { get; set; }
}
Will only map Column, and ignore mapping Column1 and Column2.
Thanks in advance for any input and advice!
This was my bad. The issue was a hidden conversion error (there was trouble converting from the decimal? that the databse was sending to the int? the class expected), and a string to GUID conversion error.

MVC3: Guid data type

I have a project that gets data from the database. I made some modifications to the database fields in the model and now I am getting the error
The 'XXX' property on 'YYY' could not be set to a 'Guid' value. You must set this property to a non-null value of type 'String'.
XXX is the key of the class and is defined in the model as
public string XXX {get; set;}
The data type of this field in my database is uniqueidentifier.
What is the "equivalence" of this data type in mvc3?
EDIT
I tried changing the datatype of XXX to
public Guid XXX {get; set;}
but I got the error
The 'UnallocatedId' property on 'YYY' could not be set to a 'Guid' value. You must set this property to a non-null value of type 'String'.
As it says in the error, you need to use the Guid type:
public Guid XXX { get; set; }

Resources