No such table sqlite when execute query on xamarin forms pcl - c#

I have a problem with the reading of the tables on the SQLite database.
my OBJ_User class:
namespace Fimap.Models
{
public class OBJ_User
{
public int DLR_Id { get; set; }
public string DLR_Username { get; set; }
public string DLR_Password_Hash { get; set; }
public object DLR_Nome { get; set; }
public string DLR_Cognome { get; set; }
public int DLR_Tipo { get; set; }
public string DLR_Azienda { get; set; }
public object DLR_Telefono { get; set; }
public object DLR_Email { get; set; }
public int DLR_Abilitato { get; set; }
public object DLR_Time_Zone { get; set; }
public object DLR_Country { get; set; }
public string DLR_Culture { get; set; }
public object DLR_Email1 { get; set; }
public object DLR_MCC_Modello_Alias { get; set; }
public object DLR_Anagrafica { get; set; }
public object DLR_Firma { get; set; }
public bool IsFIMAP { get; set; }
public bool IsSTANDARD { get; set; }
public bool IsDealerOrFimap { get; set; } //true dealer - false user
public object DLR_Tipo_Esteso { get; set; }
public object DLR_Abilitato_Esteso { get; set; }
}
}
my interface in pcl project:
public interface IDatabaseConnection
{
SQLite.SQLiteConnection DbConnection();
}
Android
[assembly: Xamarin.Forms.Dependency(typeof(DatabaseConnection_Android))]
namespace Fimap.Droid
{
public class DatabaseConnection_Android : IDatabaseConnection
{
public SQLiteConnection DbConnection()
{
var dbName = "FimapDB.db3";
var path = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), dbName);
return new SQLiteConnection(path);
}
}
}
iOS
[assembly: Xamarin.Forms.Dependency(typeof(DatabaseConnection_iOS))]
namespace App.iOS
{
public class DatabaseConnection_iOS : IDatabaseConnection
{
public SQLiteConnection DbConnection()
{
var dbName = "FimapDB.db3";
string personalFolder = System.Environment.GetFolderPath(Environment.SpecialFolder.Personal);
string libraryFolder = Path.Combine(personalFolder);
var path = Path.Combine(libraryFolder, dbName);
return new SQLiteConnection(path);
}
}
}
pcl connection (database is right connect):
database = DependencyService.Get<IDatabaseConnection>().DbConnection();
query:
var test = database.Query<OBJ_User>("SELECT * FROM OBJ_User");
when i launch the query i have this error:
SQLite.SQLiteException: no such table: OBJ_User
OBJ_User is in the dabatase with one record.
Why the connection don't mapping the table ?
database variable is right connect to database sqlite, i don't understand because database don't get mapping from sqlite file.
Solution ?
if you want other info write me in the comment, i will answer

The SQLite library doesn't know how to map the properties of type object to a sqlite column. The SQLite library supports the following column types by default: string, int, double, byte[], DateTime.

Related

Auto mapper makes error when mapping class with another class properties

I have following two class structures, its CASADetialsResponse as follows,
public class CASADetialsResponse
{
public string status { get; set; }
public string message { get; set; }
public List<object> validation { get; set; }
public Data data { get; set; }
}
public class LinkedCard
{
public string cardNumber { get; set; }
}
public class JointParty
{
public string jointName { get; set; }
}
public class Account
{
public string accountNumber { get; set; }
public string accountNickName { get; set; }
public List<LinkedCard> linkedCards { get; set; }
public List<JointParty> jointParty { get; set; }
public List<object> productValidation { get; set; }
}
public class Transaction
{
public string accountNumber { get; set; }
public string valueDate { get; set; }
public string transactionDetails { get; set; }
public string postDate { get; set; }
}
public class Data
{
public Account account { get; set; }
public List<Transaction> transactions { get; set; }
}
And the CASADetails class structure as follows,
public class CASADetails
{
public string status { get; set; }
public string message { get; set; }
public List<object> validation { get; set; }
public Data data { get; set; }
}
public class LinkedCard
{
public string cardNumber { get; set; }
}
public class JointParty
{
public string jointName { get; set; }
}
public class Account
{
public string accountNumber { get; set; }
public string accountNickName { get; set; }
public List<LinkedCard> linkedCards { get; set; }
public List<JointParty> jointParty { get; set; }
public List<object> productValidation { get; set; }
}
public class Transaction
{
public string accountNumber { get; set; }
public string valueDate { get; set; }
public string transactionDetails { get; set; }
public string postDate { get; set; }
}
public class Data
{
public Account account { get; set; }
public List<Transaction> transactions { get; set; }
}
When I use _mapper.Map<CASADetialsResponse>(casaResponse); I'm getting this error:
Error mapping types:
Mapping types:
CASADetails -> CASADetialsResponse
AccountManagement.Domain.CASADetails -> AccountManagement.Application.Dtos.CASADetails.CASADetialsResponse
Type Map configuration:
CASADetails -> CASADetialsResponse
AccountManagement.Domain.CASADetails -> AccountManagement.Application.Dtos.CASADetails.CASADetialsResponse
Destination Member:
data
This is how I map the two classes,
public class CASADetailsProfile : Profile
{
public CASADetailsProfile()
{
// Source -> Target
CreateMap<CASADetialsRequest, CASADetails>();
CreateMap<CASADetails, CASADetialsResponse>();
}
}
I just commented the public Data data { get; set; } from the both classes, and without any error its worked. I think problem is with that line. may I know the reason? please help me
The namespace for Data class is different, even though their content is the same.
Delete these
and refer to source Data class namespace or
If you don't want to delete them, add the following configuration
public class CASADetailsProfile: Profile
{
public CASADetailsProfile()
{
// Source -> Target
CreateMap<CASADetialsRequest, CASADetails>();
CreateMap<CASADetails, CASADetialsResponse>();
CreateMap<Sources.Data, Destinations.Data>();
CreateMap<Sources.Account, Destinations.Account>();
CreateMap<Sources.Transaction, Destinations.Transaction>();
CreateMap<Sources.LinkedCard, Destinations.LinkedCard>();
CreateMap<Sources.JointParty, Destinations.JointParty>();
}
}
Change Sources namespace and Destinations namespace to the namespace that you have

TextBlob is null

I am working with SQLite for the first time, I have working on a student project, and I have done a lot of research, but I cannot fix my problem. I am trying to use sqlite-net-extensions, but my TextBlob is always null. How can use the methods with WithChilder, I cannot get them to work either
This is my model class:
public class FoodNutrient
{
[PrimaryKey, AutoIncrement]
public int ID { get; set; }
public string foodname { get; set; }
public string sd { get; set; }
public string time { get; set; }
[TextBlob(nameof(nutrientsBlobbed))]
public List<NutrientItem> nutrients { get; set; }
public string nutrientsBlobbed { get; set; }
}
public class NutrientItem
{
public string name { get; set; }
public string group { get; set; }
public string unit { get; set; }
public double value { get; set; }
}
This is my database:
public class FoodDatabase
{
readonly SQLiteAsyncConnection database;
public FoodDatabase(string dbPath)
{
database = new SQLiteAsyncConnection(dbPath);
database.CreateTableAsync<FoodNutrient>().Wait();
}
public Task<int> SaveFoodNutrientAsync(FoodNutrient foodNutrient)
{
return database.InsertAsync(foodNutrient);
}
public Task<List<FoodNutrient>> GetFoodNutrientsAsync()
{
return database.Table<FoodNutrient>().ToListAsync();
//return database.GetAllWithChildren<FoodNutrient>();
}
}
You also need to use the function InsertWithChildren of the SQLiteExtensions.
Change the function SaveFoodNutrientAsync like this:
public Task<int> SaveFoodNutrientAsync(FoodNutrient foodNutrient)
{
return database.InsertWithChildrenAsync(foodNutrient);
}
This will update the TextBlob to the value it corresponds.
You will also need to use the GetAllWithChildren to get your object with the blob.
public Task<List<FoodNutrient>> GetFoodNutrientsAsync()
{
return database.GetAllWithChildren<FoodNutrient>();
}

Entity Framework throwing Null entry error at Saving, C#

I am working on Entity Framework 6 and repositories setup to do crud operations. I am trying to insert record in one of the table and getting error for null entries even duo it is not.
{"Cannot insert the value NULL into column 'UI_ID', table 'Blackpool_BPM.dbo.COURSE_INSTANCE'; column does not allow nulls. INSERT fails.\r\nThe statement has been terminated."}
The connection to database is correct as I can read data with no problem
At Generic Repository, getting data correctly, just before Save()
Table Structure
Class Model
[Table("COURSE_INSTANCE")]
public class BIZCourseInstanceEntity
{
[Key]
public int UI_ID { get; set; }
public string UnitInstanceCode { get; set; }
public string FESLongDescription { get; set; }
public string FESShortDescription { get; set; }
public string FullDescription { get; set; }
public string OwningOrganisationCode { get; set; }
public int? OwningOrganisationID { get; set; }
public string TopicCode { get; set; }
public string UnitCategory { get; set; }
public string UnitCode { get; set; }
public string FESQualificationType { get; set; }
public int? SCHOOLS { get; set; }
public int? MARKETING_GROUPS { get; set; }
}
Repository
public class BIZCourseInstanceRepository : GenericRepository<BIZCourseInstanceEntity>
{
public BIZCourseInstanceRepository() { }
public BIZCourseInstanceRepository(DbContext dbContext)
:base(dbContext)
{ }
}
Unit of work class
public class BIZ_UOF : IDisposable
{
private BIZDbContext _BIZDbContextObject = new BIZDbContext();
protected BIZCourseInstanceRepository _BIZCourseInstanceRepository;
public BIZCourseInstanceRepository BIZCourseInstanceRepository
{
get
{
if (this._BIZCourseInstanceRepository == null)
{
this._BIZCourseInstanceRepository = new BIZCourseInstanceRepository(_BIZDbContextObject);
}
return _BIZCourseInstanceRepository;
}
}
/////
public void Save()
{
_BIZDbContextObject.Database.Log = s => System.Diagnostics.Debug.WriteLine(s);
_BIZDbContextObject.SaveChanges();
}
private bool disposed = false;
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
_BIZDbContextObject.Dispose();
}
}
this.disposed = true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
DbContext
public class BIZDbContext : BaseContext<BIZDbContext>
{
public BIZDbContext() : base("_DbContext")
{ }
public DbSet<BIZCourseInstanceEntity> BIZ_CourseInstance { get; set; }
}
Generic Repository CRUD
public void InsertEntity(TEntity obj)
{
_DbSet.Add(obj);
}
Function class where Error is generating at Save()
public void InsertCourseInstance()
{
BIZCourseInstanceEntity BIZCourseInstanceEntityObject = null;
BIZCourseInstanceEntityObject = new BIZCourseInstanceEntity
{
UI_ID = 999999,
UnitInstanceCode = "KZ999999",
FESLongDescription = "LONG",
FESShortDescription = "SHORT",
FullDescription = "FULL",
OwningOrganisationCode = "E",
OwningOrganisationID = 155,
TopicCode = "04.1",
UnitCategory = "04",
UnitCode = "HE-G",
FESQualificationType = null,
SCHOOLS = 5,
MARKETING_GROUPS = 44
};
using (var _uow = new BIZ_UOF())
{
_uow.BIZCourseInstanceRepository.InsertEntity(BIZCourseInstanceEntityObject);
_uow.Save();
}
}
You need to tell Entity Framework that your ID is an identity field. If it isn't set up as that in the database, then you need to do that. Otherwise, you'll need to query for the next available ID, and then hope you don't collide with another request trying to save something at the same time.
[Table("COURSE_INSTANCE")]
public class BIZCourseInstanceEntity
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int UI_ID { get; set; }
...
}
If you absolutely have to work without any sort of database generated options for your Primary Key, you can instead use the DatabaseGeneratedOption.None value of the enum. This should be avoided to prevent collisions on your PK, but the option does exist.
I have found answer, the problem was in my database I am require to provide the Primary key which in my case is UI_ID but in my model I haven't define DatabaseGeneredOption.None, hence throwing error, Thanks for Krillgar guiding me
here is updated model
[Table("COURSE_INSTANCE")]
public class BIZCourseInstanceEntity
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int UI_ID { get; set; }
[StringLength(255)]
public string UnitInstanceCode { get; set; }
[StringLength(255)]
public string FESLongDescription { get; set; }
[StringLength(255)]
public string FESShortDescription { get; set; }
[StringLength(255)]
public string FullDescription { get; set; }
[StringLength(255)]
public string OwningOrganisationCode { get; set; }
public int? OwningOrganisationID { get; set; }
[StringLength(255)]
public string TopicCode { get; set; }
[StringLength(255)]
public string UnitCategory { get; set; }
[StringLength(255)]
public string UnitCode { get; set; }
[StringLength(50)]
public string FESQualificationType { get; set; }
public int? SCHOOLS { get; set; }
public int? MARKETING_GROUPS { get; set; }
}

Error while retrieving data from database view using code first

I have a view in my SQL database. All I want is to retrieve data from that view.
I have added POCO class.
namespace WFPersistence.DataModel
{
public class Instance
{
public Guid InstanceId { get; set; }
public DateTime? PendingTimer { get; set; }
public DateTime? CreationTime { get; set; }
public DateTime? LastUpdatedTime { get; set; }
public int? ServiceDeploymentId { get; set; }
public string SuspensionExceptionName { get; set; }
public string SuspensionReason { get; set; }
public string ActiveBookmarks { get; set; }
public string CurrentMachine { get; set; }
public string LastMachine { get; set; }
public string ExecutionStatus { get; set; }
public bool? IsInitialized { get; set; }
public bool? IsSuspended { get; set; }
public bool? IsCompleted { get; set; }
public byte? EncodingOption { get; set; }
public byte[] ReadWritePrimitiveDataProperties { get; set; }
public byte[] WriteOnlyPrimitiveDataProperties { get; set; }
public byte[] ReadWriteComplexDataProperties { get; set; }
public byte[] WriteOnlyComplexDataProperties { get; set; }
public string IdentityName { get; set; }
public string IdentityPackage { get; set; }
public long? Build { get; set; }
public long? Major { get; set; }
public long? Minor { get; set; }
public long? Revision { get; set; }
}
public class Instances : Collection<Instance>
{
}
}
This is how I am trying to map with view.
public class WFPersistenceStore : DbContext
{
public WFPersistenceStore() : base("WFPersist")
{
}
public DbSet<Instance> PersistedInstances { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Instance>().ToTable("System.Activities.DurableInstancing.Instances");
}
}
This is how I am connecting with view
using (var PersistStore = new WFPersistenceStore())
{
var result = from t in PersistStore.PersistedInstances
select t;
////
///
}
I am getting this error:
An unhandled exception of type 'System.ArgumentException' occurred in
RentalHost.exe
Additional information: The database name
'System.Activities.DurableInstancing.Instances' is invalid. Database
names must be of the form [.].
Your method should be like
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Instance>().ToTable("Instances");
}
I have resolved my issue by just putting the following line inside the constructor of my context class (i.e. WFPersistenceStore).
Database.SetInitializer<WFPersistenceStore>(null);
This wasn't mentioned anywhere clearly in official documents if i am not wrong.
The above line needed for EF6 version only but not required for earlier versions of EF.

examples from "Programming Entity Framework Code First book" don't create database

I was download examples from o'reilly site but they dont creates .sdf file. In book describes, by default, database is created in bin/debug project folder. I have installed all needed components. Debuging is passed successfully. Here source code:
namespace BreakAwayConsole
{
class Program
{
static void Main(string[] args)
{
Database.SetInitializer(
new DropCreateDatabaseIfModelChanges<BreakAwayContext>());
InsertDestination();
}
private static void InsertDestination()
{
var destination = new Destination
{
Country = "Indonesia",
Description = "EcoTourism at its best in exquisite Bali",
Name = "Bali"
};
using (var context = new BreakAwayContext())
{
context.Destinations.Add(destination);
context.SaveChanges();
}
}
}
}
namespace DataAccess
{
public class BreakAwayContext : DbContext
{
public DbSet<Destination> Destinations { get; set; }
public DbSet<Lodging> Lodgings { get; set; }
}
}
namespace Model
{
public class Lodging
{
public int LodgingId { get; set; }
[Required]
[MaxLength(200)]
[MinLength(10)]
public string Name { get; set; }
public string Owner { get; set; }
public bool IsResort { get; set; }
public Destination Destination { get; set; }
}
public class Destination
{
public int DestinationId { get; set; }
[Required]
public string Name { get; set; }
public string Country { get; set; }
[MaxLength(500)]
public string Description { get; set; }
[Column(TypeName = "image")]
public byte[] Photo { get; set; }
public List<Lodging> Lodgings { get; set; }
}
}
If you haven't specified connection string for your context, then by default database will be created at SQLEXPRESS server instead of sdf file in debug folder. Search for database named DataAccess.BreakAwayContext on your local SQLEXPRESS instance.

Categories