Windows Phone sqlite select all - sqlite

I have a query which simply does, in a table named "CUSTOMER" a select all.
This is my Table:
public class CUSTOMER : Extension.Shared
{
[PrimaryKey, Indexed]
public Guid ID { get; set; }
[Indexed]
public string FULL_NAME { get; set; }
public string PHONE_NO { get; set; }
//public string PIVA_CF { get; set; }
public DateTime? MODIFIED_ON { get; set; }
And this is the query which gives me the problem
public List<CUSTOMER> SelectAll()
{
SQLiteConnection conn = new SQLiteConnection(DatabasePath());
return conn.Query<CUSTOMER>("SELECT * FROM CUSTOMER");
}
Every times i run this operation, the query returns an error from SQLite.cs file:
if (r != SQLite3.Result.OK)
{
throw SQLiteException.New (r, String.Format ("Could not open database file: {0} ({1})", DatabasePath, r));
}
If the size can be a useful, this table has nearly 50000 records.
I have the same problem in a couple of tables with 100000 or 80000 records.
No problems with other Tables, no problem with other queries.
I can say this because since I thought the table was badly saved, I installed again and again the table, but I noticed that from the same page i can call this query without any problem, for all tables:
public List<CUSTOMER> SelectByFilter(string Filter)
{
SQLiteConnection conn = new SQLiteConnection(DatabasePath());
return conn.Query<CUSTOMER>(string.Format("SELECT * FROM CUSTOMER WHERE FULL_NAME LIKE '{0}%'", Filter));
}
I don't really know where can this error came from. I don't know any size's restriction on Sqlite3. Any help will be appreciated.

This error tells that it cannot find the database at the path given check with isolated storage tool that the database exist in that place also check you are referencing the correct path to database file in your DatabasePAth() method or else try this
public List<CUSTOMER> SelectByFilter(string Filter)
{
string dbpath = System.IO.Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "yourdatabsefilename.db");
//database is in home directory not in any subfolders. then only this code will work
SQLiteConnection conn = new SQLiteConnection(dbpath);
return conn.Query<CUSTOMER>(string.Format("SELECT * FROM CUSTOMER WHERE FULL_NAME LIKE '{0}%'", Filter));
}

Related

How to diagnose slow Entity Framework stored procedure call?

Problem: I'm calling a stored procedure through EF Core. When I run the stored procedure directly (via 'debug procedure'), it runs quickly, but it runs VERY slowly when called by EF's FromSqlRaw. So the problem appears to be when converting the returned data-table to a list of objects.
Setup:
Simple application with a list of blog posts. The stored procedure gets a hierarchical list of posts and associated users from a TPH table of posts, plus a table of users.
// Code is simplified, actually 8 parameters
SqlParameter depth_p = new SqlParameter("#depth", depth);
SqlParameter authorizedUserID_p = new SqlParameter("#authorizedUserID", authorizedUser.ID);
IQueryable<PostUser> query = postContext.PostUsers
.FromSqlRaw("Post.USP_ReadDebate #depth, #authorizedUserID",
parameters: new[] { depth_p, authorizedUserID_p });
List<PostUser> postUsers = query.ToList(); // This hangs.
26 columns are returned and converted by EF into the PostUser class.
PostUser holds 26 "ordinary" properties. No navigation properties, custom classes or any getters or setters that do any work.
public class PostUser
{
// Post fields
public Int32? ID { get; set; } // Primary Key
public String Text { get; set; }
public Guid OwnerID { get; set; }
public int? ParentID { get; set; } // nullable
public bool IsDisabled { get; set; }
public DateTime TimeCreated { get; set; }
public bool User_IsBanned { get; set; } = false;
// some others...
public PostUser() { }
}
Note: the stored procedure is very complex. It calls another stored procedure which fills a #spid table, then inserts the contents of that #SPID table into a table variable and returns that.
But again when debugged directly it returns quickly, so I think the problem is when EF Core is converting the returned data to the PostUser object.
Bottom Line: is there any way to get visibility into what EF Core is doing on the conversion to PostUser to find the problem?
Thank you!

query soft deleted records in an Azure mobile app easy table

I have a Azure mobile Easy Table Xamarin App that is a bunch of lists, reminders for myself. It works fine to add, update and delete. I want to be able to get a list of soft deleted items so I can undelete some to add them back into a list without retyping them. I cannot figure out how to do this. I see in Google searches an IncludeDeleted attribute but it does not seem to apply to the IMobileServiceSyncTable table I am using. Here is the code, but it retrieves zero records. If I run it in LinqPad 5 I get all the soft deleted records.
public async Task<IEnumerable<ListData>> GetDeletedItemsAsync()
{
await InitializeClient();
await SyncItems();
try
{
IEnumerable<ListData> items = await listdata
.Where(listdata => listdata.Deleted == true )
.ToEnumerableAsync();
return new ObservableCollection<ListData>(items);
}
catch (MobileServiceInvalidOperationException msioe)
{
Debug.WriteLine(#"Invalid sync operation: {0}", msioe.Message);
}
catch (Exception e)
{
Debug.WriteLine(#"Sync error: {0}", e.Message);
}
return null;
}
Here is the Class:
public class ListData
{
public string id { get; set; }
[JsonProperty(PropertyName = "listname")]
public string ListName { get; set; }
[JsonProperty(PropertyName = "itemdata")]
public string ItemData { get; set; }
[JsonProperty(PropertyName = "itemdetail")]
public string ItemDetail { get; set; }
[JsonProperty(PropertyName = "deleted")]
public Boolean Deleted { get; set; }
// *** Enable Optimistic Concurrency *** //
[Version]
public string Version { get; set; }
}
What am I missing? Thanks.
Per my understanding, you could try to change your SyncItems method as follows:
private async Task SyncItems()
{
var queryName = $"incsync:s:{typeof(ListData).Name}";
var query = listDataTable.CreateQuery().IncludeDeleted();
await listDataTable.PullAsync(queryName, query);
}
And you could use fiddler to capture the network traces when invoking the above method, then you could check the response and find whether you could retrieve the deleted items.
Then you could leverage DB Browser for SQLite or any other tool to check your local SQLite database and verify your table records to narrow this issue.
The way to do this is to go directly to the server using an IMobileServiceTable object. It is pretty simple. You can then use the IncludeDeleted directive on the query. Case solved.

Entity Framework 6 Code First duplicates

I'm trying to learn EFCF but I stumbled upon a records duplication problem and I can't find solution anywhere on the internet (or I just don't know what to search). The DbContext class is as follows:
public class Database : DbContext
{
public Database() : base("name=DBconnString")
{
}
public DbSet<Human> People { get; set; }
public void human_add_new(int _rank, String _name, String _surname)
{
Human dummy = new Human(_rank, String _name, String _surname);
People.Add(dummy);
SaveChanges();
}
}
And the human class is as follows:
public class Human
{
[Index(IsUnique = true)]
public Int16 ID { get; set; }
public int rank { get; set; }
public String name { get; set; }
public String surname { get; set; }
}
Now, the problem is whenever I run my code and it executes this:
human_add_new(3, "Noname", "Noname");
a new record is created, thus creating duplicates in my database (so if I run the code 5 times, 5 identical records will be created). How do I prevent that? [Index(IsUnique = true)] doesn't seem to help here, cause in a larger database it may happen that 2 people have the same name or the same surname.
Here's how it looks like in MS SQL Studio: imgur
You applied a Unique Index to the ID property - if you want unique names/surnames, you'll have to apply a Unique constraint to them as well.
(According to your imgur picture, IDs are distinct, other fields are the same)

The member with identity does not exist in the metadata collection. Parameter name: identity

We are using EF Code First 4.3.1.
We are developing an ASP.NET Web Role referring to multiple class libraries.
There are two class libraries each containing classes and an individual DBcontext.
Lets say the Library1 has classes A and B.
DBcon1: DbSet and DbSet
Lets say the Library2 has classes C and D.
Class C{
[Key]
public int CId{ get; set;}
[Required]
public virtual A referencedA {get; set;}
}
DBcon2: DbSet<C> and DbSet<D>
When I try to use the DBcon2 as such:
using (var con = new DBcon2())
{
C vr = new C();
vr.CId= 1;
vr.referencedA = DBCon1.As.First();
con.Cs.Add(vr);
con.SaveChanges();
}
I get an exception as:
"The member with identity does not exist in the metadata collection.
Parameter name: identity"
Both DBCon1 and DBcon2 are using the sane SQL Server Database "SampleDB".
Please point me in the right direction.
I got this error and fixed it by not trying to set the navigation property in the related table, just set the foreign key id instead
eg
public class Student()
{
public int StudentId { get; set; }
public string StudentName { get; set; }
public int CourseId { get; set; }
public virtual Course Course { get; set; }
}
public class Course()
{
public int CourseId { get; set; }
public string CourseName { get; set; }
public virtual ICollection<Student> Students { get; set; }
}
Main code:
var myCourse = new Course();
var myCourseId = 1;
var student = new Student() {
CourseId = myCourseId
// Course = myCourse <-- this would cause the error
}
Might not be your issue but maybe it will point you in the right direction and hopefully will help someone else.
The exception is a bit cryptic, but pretty clear if you realise that a context needs information about entities (metadata) to be able to write sql statements. Thus, your DBcon2 context has no clue where to find the primary key of an A, because it has no metadata about A.
You could however set an integer property A_Id (or the like), but then you'll have to write custom code to resolve it to an A.
Another option is to merge (parts of) the contexts, if possible.

How to get the mysql data in ASP.net MVC3?

I'm trying to get my mysql data in ASP.net MVC3.
The mysql Database Name is supply_db and table name is xcart_orders.
ASP.net code is like below,
(Im just following my book, and just switch to my DB info but it does not work :( )
(I will omit using and namespace)
Web.Config File,
<add name="EFMysqlContext" connectionString="server=XXX.XXX.XXX.XX;User Id=root;pwd=xxx;Persist Security Info=True;database=supply_db"
providerName="Mysql.Data.MySqlClient" />
Abstract/IXcartOrdersRepository.cs
public interface IXcartOrdersRepository
{
IQueryable<XcartOrder> xcart_orders { get; }
}
/Concrete/EFXcartOrderRepository.cs
public class EFXcartOrdersRepository : IXcartOrdersRepository
{
private EFMysqlContext context = new EFMysqlContext();
public IQueryable<XcartOrder> xcart_orders
{
get { return context.xcart_orders; } // I thought the 'xcart_orders' should be match with db table name, isn't it?
}
}
/Entities/XcartOrder.cs
public class XcartOrder
{
[Key]
public int orderid { get; set; }
public string login { get; set; }
public string membership { get; set; }
public decimal subtotal { get; set; }
}
and In my controller,
IXcartOrdersRepository XcartOrdersRepository = new EFXcartOrdersRepository();
int orderCnt = XcartOrdersRepository.xcart_orders.Count();
then error occur, the error message say "{"Table 'supply_db.XcartOrders' doesn't exist"}"
I think I could connect to db, but couldn't get the table.
anybody know which part do I need to change?
Thank you!
can you decorate your Xcartorder class with the Table attribute to explicitly specify the desired name?
[Table("xcart_orders")]
public class XcartOrder
{
...
edit: attribute syntax

Resources