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>();
}
Related
I have issue that I hope someone here will be able to help me.For this exercise I`m using aspnetboilerplate framework.
So I create 3 entity and they ALL work good (at least I guess they work good)
Little bit recap of project
One Recepie HAVE one or more Ingredient
Ingrident.cs
public class Ingrident : Entity
{
public string Name { get; set; }
public Master Master { get; set; }
public int? MasterId { get; set; }
public Recepie Recepie { get; set; }
public int? RecepieId { get; set; }
}
Master.cs
public class Master : Entity
{
public string Name { get; set; }
public string? Image { get; set; }
public string? ShortDescription { get; set; }
public string? FullDescription { get; set; }
public string? Keywords { get; set; }
public string Slug { get; set; }
public int? Count { get; set; }
public List<Ingrident> Ingridents { get; set; }
}
Recepie.cs
public class Recepie : Entity
{
public string RecepieName { get; set; }
public Ingrident Ingridents { get; set; }
}
With this database structure I can add Recepie and add only one ingredient when I try to send [] of Ingredient its show me DTO error.
And here is RecepieAppService.cs
public class RecepieAppService : AsyncCrudAppService<IndexIngrident.Entities.Recepie,RecepieDto>
{
private readonly IRepository<IndexIngrident.Entities.Recepie> _repository;
private readonly IRepository<IndexIngrident.Entities.Ingrident> _ingRepository;
public RecepieAppService(IRepository<IndexIngrident.Entities.Recepie> repository, IRepository<IndexIngrident.Entities.Ingrident> ingRepository)
: base(repository)
{
_repository = repository;
_ingRepository = ingRepository;
}
public List<RecepieFullGetDto> GetAllIncluded()
{
var result = _repository.GetAllIncluding(x => x.Ingridents , x => x.Ingridents.Master);
Debug.WriteLine(result);
return ObjectMapper.Map<List<RecepieFullGetDto>>(result);
}
}
RecepieDto.cs
[AutoMap(typeof(IndexIngrident.Entities.Recepie))]
public class RecepieDto : EntityDto
{
public string RecepieName { get; set; }
public IngridentRecepieDto Ingridents { get; set; }
}
public class IngridentRecepieDto : EntityDto
{
public string Name { get; set; }
public int RecepieId { get; set; }
}
Using AsyncCrudAppService my CRUD is automatically generated and I`m able to create new Recepie but when I try to do something like this
I get error
you need to add the mapping of objects in both directions, [AutoMapTo (typeof (RecepieDto))] and [AutoMapFrom (typeof (Recepie))], and verify that you have the class, inherits AutomapperProfile
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.
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; }
}
I have this model class:
public class MembershipSerial
{
[HiddenInput(DisplayValue=false)]
public int Id { get; set; }
[HiddenInput(DisplayValue=false)]
public string Serial { get; set; }
[Required]
[Display(Name="Membership Serial")]
public string SerialConfirmed { get; set; }
}
I am using EF code-first approach, I would like to check the value of the Serial vs SerialConfirmed and find any Serial which is equal to SerialConfirmed.
I tried below but i get a null exception and don't know how to solve this?
public ActionResult Checkout(UserDetails Details)
{
if (Details.MembershipSerial.Serial.Any().ToString() == Details.MembershipSerial.SerialConfirmed)
{
return View("UserSerial");
}
return View();
}
public class UserDetails : IdentityUser
{
public virtual DeliveryDetails DeliveryDetails { get; set; }
public virtual UserOrders UserOrders { get; set; }
public virtual MembershipSerial MembershipSerial { get; set; }
}
Edit:
public class MembershipSerial
{
[HiddenInput(DisplayValue=false)]
public int Id { get; set; }
[HiddenInput(DisplayValue=false)]
public string Serial { get; set; }
[Required]
[Display(Name="Membership Serial")]
public string SerialConfirmed { get; set; }
}
public class DeliveryDetails
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Phone { get; set; }
public string Company { get; set; }
public string Address { get; set; }
public string AddressLine2 { get; set; }
public string District { get; set; }
public string Province { get; set; }
}
public class UserOrders
{
public int Id { get; set; }
public string ProductName { get; set; }
}
public class MyDbContext : IdentityDbContext<UserDetails>
{
public MyDbContext()
: base ("EFDbContext")
{
}
public System.Data.Entity.DbSet<MembershipSerial> MembershipSerial { get; set; }
public System.Data.Entity.DbSet<DeliveryDetails> DeliveryDetails { get; set; }
public System.Data.Entity.DbSet<UserOrders> UserOrders { get; set; }
}
Any help is appreciated. Thanks in advance.
Your if statement should be like this:
if (Details.MembershipSerial.Serial == Details.MembershipSerial.SerialConfirmed)
Serial and Serial Confirmed are strings so you can just compare them
If you're trying to compare any Serial in the database with the SerialConfirmed that the user is Checking Out then you need a variable to hold a new instance of your connection string: assuming that MemberShipSerial is a table in your database...
using(var db = new ConnectionString())
{
if(db.MembershipSerial.Any(x => x.Serial.ToUpper() == Details.MembershipSerial.SerialConfirmed.ToUpper())
{
/*do something*/
}
}
if you just want to compare Serial and SerialConfirmed based on what the user typed in then use
if(Details.MembershipSerial.Serial.ToUpper() == Details.MembershipSerial.SerialConfirmed.ToUpper())
if the second option returns a null exception then you have to debug on the CheckingIn Action and see if what those properties are holding the values you are expecting
I'm very new to MVC/LINQ so bear with me. I'm wanting to check if that TransmissionStatus var is false and if so linq to db to pull the appropriate failed message.
class AuditLogManagement
{
public int ID { get; set; }
public DateTime Date { get; set; }
public string MsgType { get; set; } //possibly enum?
public AuditLogEventDetails EventDetails { get; set; }
public string MsgContents { get; set; }
public bool TransmissionStatus { get; set; }
public string FailedTransmissionMsg
{
get
{
if (!TransmissionStatus)
{
//linq to db to return failed xmission message
}
}
}
}