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+"'");
Related
I am totally not getting this, because I have used this library in Xamarin apps for several years.
I have this base class that contains properties common in all db items:
public class BaseItem
{
[PrimaryKey, AutoIncrement]
public int ID { get; set; } = 0; // SQLite ID
public long CreatedTimeSeconds { get; set; } = DateTime.Now.ToUnixTimeSeconds();
public long ModifiedTimeSeconds { get; set; } = DateTime.Now.ToUnixTimeSeconds();
}
Now, I derive from it:
[Table("CategoryTable")]
public class Category : BaseItem
{
public int CategoryTypeID { get; set; } = (int)CategoryType.Invalid;
public string Name { get; set; } = string.Empty;
public string Description { get; set; } = string.Empty;
}
Here's a simplified version of what I'm seeing:
public class DBWorld
{
ISQLiteService SQLite { get { return DependencyService.Get<ISQLiteService>(); } }
private readonly SQLiteConnection _conn;
public DBWorld()
{
_conn = SQLite.GetConnection("myapp.sqlite");
}
public void TestThis()
{
_conn.CreateTable<Category>();
var category = new Category();
category.Name = "This Should Work";
int recCount = connection.Insert(category);
// at this point recCount shows as 1, and category.ID shows as zero.
// I thought Insert was supposed to set the autoincrement primary key
// regardless, it should be set in the database, right? So...
var categoryList = connection.Query<Category>($"SELECT * FROM {DBConstants.CategoryTableName}");
// at this point categoryList[0] contains all the expected values, except ID = 0
}
}
I am obviously missing something, but for the life of me, I can't figure out what...
Like so many other bizarre things that happen in the Visual Studio Xamarin world, when I went back later, this worked the way all of us expect. I guess Visual Studio was just tired and needed to be restarted.
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");
I am stuck. I'm creating a database of authors and run to a problem. I need to save value Umrti (date of death) to database as null, but it always save that value as 01.01.0001. I tried few things and now my code looks like this:
public class AutorDetailModel
{
public int Id { get; set; }
[Required]
public string Jmeno { get; set; }
[Required]
public string Prijmeni { get; set; }
public string ProstredniJmeno { get; set; }
[DotvvmEnforceClientFormat]
public DateTime Narozeni { get; set; }
[DotvvmEnforceClientFormat]
public DateTime? Umrti { get; set; }
public string Bio { get; set; }
public string Narodnost { get; set; }
public byte Obrazek { get; set; }
}
And in service like this:
public async Task UpdateAutorAsync(AutorDetailModel autor)
{
using (var dbContext = CreateDbContext())
{
var entity = await dbContext.Autors.FirstOrDefaultAsync(s => s.Id == autor.Id);
entity.Jmeno = autor.Jmeno;
entity.Prijmeni = autor.Prijmeni;
entity.ProstredniJmeno = autor.ProstredniJmeno;
entity.Narozeni = autor.Narozeni;
entity.Umrti = autor.Umrti;
entity.Bio = autor.Bio;
entity.Narodnost = autor.Narodnost;
entity.Obrazek = autor.Obrazek;
await dbContext.SaveChangesAsync();
}
}
However, autor.Umrti still gives me this error:
Cannot implicitly convert type 'System.DateTime?' to 'System.DateTime'. An explicit conversion exists (are you missing a cast?)
I am really stuck and will appreciate any advice. Thanks
And sorry for my bad english :)
you must check Umrti is null or not
public async Task UpdateAutorAsync(AutorDetailModel autor)
{
using (var dbContext = CreateDbContext())
{
var entity = await dbContext.Autors.FirstOrDefaultAsync(s => s.Id == autor.Id);
entity.Jmeno = autor.Jmeno;
entity.Prijmeni = autor.Prijmeni;
entity.ProstredniJmeno = autor.ProstredniJmeno;
entity.Narozeni = autor.Narozeni;
if(autor.Umrti!=null)
entity.Umrti = autor.Umrti;
entity.Bio = autor.Bio;
entity.Narodnost = autor.Narodnost;
entity.Obrazek = autor.Obrazek;
await dbContext.SaveChangesAsync();
}
}
If you're using SQL Server (possibly other Database engines too) then you can't save a NULL value in a DateTime field.
You'll have to convert the NULL to a date, any date, to save it in the db. Typically SQL Server uses '1900-01-01' to represent a NULL date. In most cases that's fine as, unless you are working with historical data around the end of the 18th Century, it won't clash with your valid data. When reading from the db you can convert all dates with a value of '1900-01-01' to null in your code, and when writing to the db if the value in code is null convert it to '1900-01-01'.
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);
I have a problem with strange generated SQL in ef4 ctp5.
I have simple model with mapping :
[Table("post_auction")]
public class PostAuction
{
[Key,Column(Name="Id"),DatabaseGenerated(System.ComponentModel.DataAnnotations.DatabaseGenerationOption.Identity)]
public int Id { get; set; }
[Column(Name = "Number")]
public int Number { get; set; }
[Column(Name = "Label")]
public string Label { get; set; }
[Column(Name = "Description")]
public string Description { get; set; }
[Column(Name = "CategoryId")]
public int PostAuctionCategoryId { get; set; }
[Column(Name = "PriceCZK")]
public int PriceCZK { get; set; }
[NotMapped]
public bool IsAuctionPhotoExitst
{
get
{
if (File.Exists(HttpContext.Current.Server.MapPath("~/Public/Images/Posts/Thumbs/small_" + this.Number + ".jpg")))
return true;
return false;
}
}
}
and my linq query is :
_rovastampDbContext.PostAuctions.Where(x => x.PostAuctionCategoryId == auctionId).OrderBy(x => x.Id).ToList();
Ef4 profiler shows me
SELECT
[Project1].[Id] AS [Id],
[Project1].[Number] AS [Number],
[Project1].[Label] AS [Label],
[Project1].[Description] AS [Description],
[Project1].[CategoryId] AS [CategoryId],
[Project1].[PriceCZK] AS [PriceCZK]
FROM
(SELECT
[Extent1].[Id] AS [Id],
[Extent1].[Number] AS [Number],
[Extent1].[Label] AS [Label],
[Extent1].[Description] AS [Description],
[Extent1].[CategoryId] AS [CategoryId],
[Extent1].[PriceCZK] AS [PriceCZK]
FROM
[dbo].[post_auction] AS [Extent1]
WHERE
[Extent1].[CategoryId] = 1 /* #p__linq__0 */) AS [Project1]
ORDER BY
[Project1].[Id] ASC
My question is a pretty simple : Why ef4 generate that complicated query, when right one is
SELECT ...
FROM TABLE
WHERE CategoryId = 1
ORDER BY Id ASC
Thanks for your advice :)
Martin
EDIT : If I let EF to create db automatic, the problem with query persists...
Excellent question. I'm guessing that it's a bug, since my (edmx-generated) Entity Framework context doesn't produce a projection the way yours does. I would report it as a bug.
Yeah for sure, looks like Beta-garbled code gen to me. I just tried it too with LINQ-SQL, nothing similar. Be sure to report it!