How to create database and table in sqlite programatically using monotouch? - sqlite

Can any body help me about, how to create simple database and tables programatically and insert values ,step by step procedure in sqlite using monotouch.I am new to this technology .
Thank you..

If you're using sqlite-net (which I highly recommend) you can simply call:
Model
public class Stock
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
[MaxLength(8)]
public string Symbol { get; set; }
}
Create
var db = new SQLiteConnection("stocks.db");
db.CreateTable<Stock>();
Insert
var s = db.Insert(new Stock() {
Symbol = symbol });
Query
return db.Query ("select * from Valuation where StockId = ?", stock.Id);

Related

dapper left join & mapping query

There is one-to-many relation between Brand and Campaign entities,
With given Id I need to select Campaign and related Brand entity along with it.
TO do so:
public async Task<Campaign> GetAsync(int id)
{
using var dbConnection = _context.CreateConnection();
string query = #"SELECT c.[Id], c.[BrandId], c.[StartDate],
c.[EndDate],b.[Id] FROM [dbo].[Campaign] c
left join [dbo].[Brand] b on c.[BrandId] = b.[Id]
WHERE c.[Id] = #Id";
var campaign = await dbConnection.QueryAsync<Campaign, Brand, Campaign>(query, (campaign, brand) =>
{
campaign.Brand = brand;
return campaign;
}, splitOn: "BrandId", param: new { Id = id });
return campaign.FirstOrDefault();
}
code above not throws exception but child brand entity is not correct.(its dummy record, and BrandId is 0 whereas its valu is 5 in database)
whats missing here?
entity def:
public class Campaign : SqlEntityBase
{
public int BrandId { get; set; }
public DateTime? StartDate { get; set; }
public DateTime? EndDate { get; set; }
public Brand Brand { get; set; }
}
public class Brand : SqlEntityBase
{
public string Name { get; set; }
public List<Campaign> Campaign { get; set; } = new List<Campaign>();
}
Your SQL query doesn't make sense. You're splitting on BrandId in dapper but you never select anything to do with the brand in the query. With your current code, dapper is parsing the SQL column Id into your Campaign POCO (which it cant do because there isn't a property called Id nor have you anything mapped to it in the campaign class).
And then it see's BrandId and then parses everything after that into the Brand POCO, but your remaining columns that you're selecting are the start and end dates for the campaign.
In summary: You need to include the Brand data into the SQL query. You're joining onto the table, but only selecting the campaign data.

Linq2db create table with DateTime2(3) fails when using in memory db and SQLiteDataProvider

I am trying to create table in memory db using Linq2Db, and SQLiteDataProvider in a netcore3.1 application.
And if mapping class has a property with attribute
[Column(DataType=DataType.DateTime2, Precision=3), Nullable ]
it gives me the following syntax error :
Microsoft.Data.Sqlite.SqliteException (0x80004005): SQLite Error 1: 'near ")": syntax error'.
I dig for the query it generates and its this:
CREATE TABLE [testTable]
(
[Id] INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
[Created] DateTime2(3, ) NULL
)
Here is an example that I'm trying:
using System;
using LinqToDB;
using LinqToDB.Data;
using LinqToDB.Mapping;
namespace InMemoryDb
{
class Program
{
static void Main(string[] args)
{
DataConnection.AddConfiguration("default", "Data Source=Sharable;Mode=Memory;Cache=Shared",
new LinqToDB.DataProvider.SQLite.SQLiteDataProvider("SQLite.MS"));
DataConnection.DefaultConfiguration = "default";
using var db = new DataConnection("default");
db.CreateTable<TestTable>();
}
[Table(Schema="dbo", Name="testTable")]
public class TestTable
{
[Column(DataType=DataType.Int32), PrimaryKey, Identity]
public int Id { get; set; }
[Column(DataType=DataType.DateTime2, Precision=3), Nullable]
public DateTime? Created { get; set; }
}
}
}
why its generates query with DateTime2(3, ) and not a correct one DateTime2(3)?
Try this as workaround
[Column(DbType="DateTime2(3)", Nullable ]
You can use possibility of linq2db to define schema for several databases.
Note that there is no DateTime type in SQLite.
[Table(Schema="dbo", Name="testTable")]
public class TestTable
{
[Column(DataType=DataType.Int32), PrimaryKey, Identity]
public int Id { get; set; }
[Column(Configuration=ProviderName.SQLite, DataType=DataType.DateTime2), Nullable]
[Column(DataType=DataType.DateTime2, Precision=3), Nullable]
public DateTime? Created { get; set; }
}

SQLite Xamarin.forms dosn't return the saved Data

I stuck with Xamarin.Forms SQLite.
i use this NuGet package : sqlite-net-pcl
My SQLITE Tables
I want to save the Data from my Table to a Variable with this following code
SQLiteConnection myconnection = new SQLiteConnection(Constants.DatabasePath);
SQLiteCommand cmd = new SQLiteCommand(myconnection);
myconnection.CreateTable<Modul>();
var Mods = myconnection.Query<Modul>("SELECT * FROM Modul");
Mods returns with = Count=0;
But i have saved Data. Click here
My modul class:
MoulID has Primary Key on Top [Primarykey]...
public int ModulID { get; set; }
public string Modul_Name { get; set; }
I will include my existing Database from Here
with this class
public class{
public const string DatabaseFilename = "VocalDB.db";
public static string DatabasePath
{
get
{
var basePath = "D:/C#-Projets/Vocabul/Vocabul/Vocabul/DataBase/";
return Path.Combine(basePath, DatabaseFilename);
}
}
}
In your code you create the table then you execute the query... I think the table is empty after you have created it.
myconnection.CreateTable<Modul>();
var Mods = myconnection.Query<Modul>("SELECT * FROM Modul");

How to fix a DateTime update issue in Xamarin.Forms?

I am using xamarin forms. I have some issue on datetime field in SQLite update.
The following Table in I am using:
public class DataTable
{
[PrimaryKey, AutoIncrement]
public int ID { get; set; }
public int WorkOrderId { get; set; }
public Nullable<DateTime> TargetDateTime { get; set; }
}
For DatePicker.Date, I am using DatePicker in design with the selection of any date:
DateChange dateChange=new DateChange();
dateChange.WorkOrderId=1;
dateChange.RescheduleDate=DatePicker.Date;
AddMwoReschedule(dateChange);
This is the update statement, I am using:
public List<EngMwoReschedulingTxn> AddMwoReschedule(DateChange dateChange)
{
DateTime dt = new DateTime();
dt = dateChange.RescheduleDate;
conn.Query<DataTable>("update DataTable set TargetDateTime='" + dt + "' where WorkOrderId='"+engMwoReschedulingTxn.WorkOrderId+"'");
}
Result:
The Updated TargetDateTime for table DataTable comes like below:
01-01-0001 00:00:00
Can anyone help me solve this issue?
this is working fine using LinQ code. I am using the query like this: conn.Query("update DataTable set TargetDateTime='" + dt.Ticks + "' where WorkOrderId='"+engMwoReschedulingTxn.WorkOrderId+"'");

Entity Framework : adding record with related data

I have a very simple Situation with 2 tables
public class Movie
{
[Key]
public Guid ID { get; set; }
public string Name { get; set; }
public byte[] Hash { get; set; }
public int GenreID{ get; set; }
[ForeignKey("GenreID")]
public virtual Genre genre{ get; set; }
}
and
public class Genre
{
public int ID { get; set; }
public string Name { get; set; }
}
Now, in an import sequence I want to create new movies and link the Genre with the existing entries in the Genre table or create new Genre entries if they don't exist.
Movie m = new Movie();
m.ID = Guid.NewGuid();
IndexerContext db = new IndexerContext();
var genre = db.Genre.Where(g => g.Name== genreValue).FirstOrDefault();
if(genre!= null)
{
m.GenreID= genre.GenreID;
}
else
{
genre= new Genre();
genre.Name = genreValue;
db.Genres.Add(genre);
var genreCreated= db.Genre.Where(g => g.Name== genreValue).FirstOrDefault();
m.GenreID= genreCreated.GenreID;
}
Now the problem is, it doesn't work. The last line fails because genreCreated is null.
Plus I think I must doing it wrong - it can't be that difficult in Entity Framework.
can anyone help me?
db.Genres.Add(genre);
This does not send insert statement to database - this instructs entity framework that new record should be inserted when saving changes. Genre will be saved (and created id available) after you call db.SaveChanges(); As for now, you do not have save call, so genreCreated is null.
In your situation - fix is simple, you do not need to select genreCreated from db. Just setting m.Genre to new value should do the job
Movie m = new Movie();
m.ID = Guid.NewGuid();
IndexerContext db = new IndexerContext();
var genre = db.Genre.Where(g => g.Name== genreValue).FirstOrDefault();
if(genre! = null)
{
m.GenreID = genre.GenreID;
}
else
{
genre = new Genre();
genre.Name = genreValue;
m.Genre = genre;
}
db.SaveChanges(); //m.GenreID will automatically be set to newly inserted genre
After the add statement you need to save it:
Try
genre= new Genre();
genre.Name = genreValue;
db.Genres.Add(genre);
db.SaveChanges();

Resources