How To Read and Write Records In SQLite Using SQLite Net Extensions? - sqlite

Here is the documentation I've looked at and may be helpful: Sample SQLite OneToMany Unit Test and General Read and Write Documentation in Readme
My use-case is that I've already inserted an Item and I am now editing an Item. So I will need to basically update the Item record and insert n ItemPhoto records. Basically, I'mtalking about the case of SaveItem(..) where Item.Id != 0.
It seems that when I step through the code to write to the database I am seeing all of the keys being assigned to the objects in memory appropriately. However, later when I go to read an Item by calling GetWithChildren(..) in every case except one the ItemPhotos property has a Count of 0. The only time that ItemPhotos actually gets populated is the case when the ItemPhotoId is 0. My best guess is that somehow the ItemPhotoId is not being set before GetWithChildren(..) is run and then it only works when the default in-memory value of 0 actually matches the database's ItemPhotoId for the given Item.
Here is my code showing the models and the read and write code:
public class Item
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
public string Text { get; set; }
public string Description { get; set; }
[OneToMany(CascadeOperations = CascadeOperation.All)]
public List<ItemPhoto> ItemPhotos { get; set; }
}
public class ItemPhoto
{
[PrimaryKey, AutoIncrement]
public int ItemPhotoId { get; set; }
[ForeignKey(typeof(Item))]
public int ItemId { get; set; }
public string FileLocation { get; set; }
[ManyToOne] // Many to one relationship with Item
public Item Item { get; set; }
}
class SqlLiteDataStore
{
static SQLiteConnection Database;
...
public Item GetItem(int id)
{
return Database.GetWithChildren<Item>(id, true);
}
public Item SaveItem(Item item)
{
// Simpler Attempt #1
// Database.InsertOrReplaceWithChildren(item);
// return item;
// Manual Attempt #2
if (item.Id != 0)
{
foreach (var photo in item.ItemPhotos)
{
if (photo.ItemPhotoId == 0)
Database.Insert(photo);
}
Database.UpdateWithChildren(item);
return item;
}
else
{
Database.InsertWithChildren(item, true);
return item;
}
}
...
}

Well I fixed it by dropping the existing tables and recreating them and beforehand just renaming the ItemPhoto's ItemPhotoId property to Id. Maybe the library assumes the primary key name of Id or maybe I changed something else along the way in terms of the models that just needed the tables to be recreated instead of migrated? Also, the simpler attempt at saving with just the Database.InsertOrReplaceWithChildren(item); seems to work just fine so I'm going with that for what it's worth.

Related

Mapping SQL View in EF Core 5 - SaveChanges

I'm trying to add a view as a Navigation Property of an entity.
public class Schedule
{
public int Id { get; set; }
public decimal ScheduledQuantity { get; set; }
public ScheduleDetails ScheduleDetails { get; set; }
}
public class ScheduleDetails
{
public int ScheduleId { get; set; }
public decimal BadQuantity { get; set; }
public Schedule Schedule { get; set; }
}
with mappings:
public class ScheduleDetailMap : IEntityTypeConfiguration<ScheduleDetails>
{
public void Configure(EntityTypeBuilder<ScheduleDetails> builder)
{
builder.ToView("vwScheduleDetails", "ShopOrders");
builder.HasKey(t => t.ScheduleId);
builder.HasOne(p => p.Schedule).WithOne(s => s.ScheduleDetails);
}
}
public class ScheduleMap : IEntityTypeConfiguration<Schedule>
{
public void Configure(EntityTypeBuilder<Schedule> builder)
{
builder.ToTable("Schedules");
builder.HasKey(t => t.Id);
builder.Property(t => t.Id).UseIdentityColumn();
}
}
when I query it works fine. However if I add a new Schedule record.
var schedule = new Schedule
{
ScheduledQuantity = 100,
ScheduleDetails = new ScheduleDetails()
};
context.Schedules.Add(schedule);
context.SaveChanges();
I get an exception saying " The entity type 'ScheduleDetails' is not mapped to a table, therefore the entities cannot be persisted to the database. Use 'ToTable' in 'OnModelCreating' to map it."
Is there anyway to get EF to ignore saving this 'entity'?
This is kind of an old question, but for anyone having similar issues - in my case the problem lied in navigation properties in my view. I had some leftover properties in view's class, because its code was copied from other entity. By removing those properties, the error was gone.
This doesn't really help if you want to use navigation properties in your code, but it may help someone to continue their search.

SQLite.NET PCL returning 0 in all instances of autoincrement primary key

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.

ASP.NET MVC: How to Insert Data Into Multiple Tables?

I have two tables (NPG_Chemical and NPG_Chemical_Synonym):
public partial class NPG_Chemical
{
[Key]
[Column(TypeName = "numeric")]
public decimal NPG_Chemical_ID { get; set; }
[StringLength(256)]
public string Chemical { get; set; }
}
public partial class NPG_Chemical_Synonym
{
[Key]
[Column(TypeName = "numeric")]
public decimal NPG_Chemical_Synonym_ID { get; set; }
[ForeignKey("NPG_Chemical_ID")]
[Column(TypeName = "numeric")]
public decimal NPG_Chemical_ID { get; set; }
[StringLength(512)]
public string Synonym { get; set; }
}
In the NPG_ChemicalController I have something like:
[HttpPost]
public ActionResult Create(NPG_ChemicalViewModel model)
{
using (var context = new NPG_Model())
{
var chemical = new NPG_Chemical();
chemical.Chemical = model.NPG_Chemical.Chemical;
context.NPG_Chemical.Add(chemical);
var synonym = new NPG_Chemical_Synonym();
synonym.Synonym = model.NPG_Chemical_Synonym.Synonym;
synonym.NPG_Chemical_ID = chemical.NPG_Chemical_ID;
context.NPG_Chemical_Synonym.Add(synonym);
context.SaveChanges();
}
return View();
}
and NPG_ChemicalViewModel:
namespace NPG_Administrative_Utility.Models
{
public class NPG_ChemicalViewModel
{
public NPG_ChemicalViewModel()
{
NPG_Chemical = new NPG_Chemical();
NPG_Chemical_Synonym = new NPG_Chemical_Synonym();
}
public NPG_Chemical NPG_Chemical { get; set; }
public NPG_Chemical_Synonym NPG_Chemical_Synonym { get; set; }
}
}
When I try to create a view based on NPG_ChemicalViewModel, it shows:
Can any one help me on this?
You'll need a view model. At the simplest, you can just do something like:
public class NPG_ChemicalViewModel
{
public NPG_ChemicalViewModel()
{
NPG_Chemical = new NPG_Chemical();
NPG_Chemical_Synonym = new NPG_Chemical_Synonym();
}
public NPG_Chemical NPG_Chemical { get; set; }
public NPG_Chemical_Synonym NPG_Chemical_Synonym { get; set; }
}
Then, change your action to accept this:
public ActionResult Create(NPG_ChemicalViewModel model)
In your view, you would generate the individual properties like:
#Html.EditorFor(m => m.NPG_Chemical.Chemical)
However, it's far better to only include the properties on your view model that you want to be edited:
public class ChemicalViewModel
{
public string Chemical { get; set; }
public string Synonym { get; set; }
}
Then, in your action, you just map this posted data where it should go:
var chemical = new NPG_Chemical();
chemical.Chemical = model.Chemical;
context.NPG_Chemical.Add(chemical);
var synonym = new NPG_Chemical_Synonym();
synonym.Synonym = model.Synonym;
synonym.NPG_Chemical_ID = chemical.NPG_Chemical_ID;
context.NPG_Chemical_Synonym.Add(synonym);
That said, there's some significant issues with your code here. First, it looks like you're dealing with a one-to-one or one-to-many relationship here between Chemical and Synonym, but right now, you have no foreign keys being utilized. You should add a navigation property to your synonym class:
[ForeignKey("NPG_Chemical_ID")]
public NPG_Chemical Chemical { get; set; }
That tells Entity Framework that you have a relationship and among other things allows it to automatically fill in IDs as necessary. For example, with that, you could now simply do:
synonym.Chemical = chemical;
Instead of directly referencing the ID. That way, if the id is autogenerated or otherwise unknown before saving, the relationship will still be preserved. Whereas, without it, you'd have to save chemical first, set the autogenerated id on synonym and then save the synonym in a separate transaction.
Second, if you're going to use keys typed as "numeric". Then, you're going to be responsible for generating a unique numeric string for each record. That's a huge pain, as it's going to require checking a proposed id against other existing record ids before actually saving. Otherwise, you run the risk of a primary key collision. It's far better to use a standard autoincrementing PK or barring that, at least a GUID, where you're assured a reasonably low risk of collisions occurring.
Third, you should absolute not use using with your context. Here it's not a big deal, since, you're only saving and not reading data from the database, but in a typical view, lazy-loading will kick you in the posterior quick doing that. Your context should be request-scoped, either as an instance variable on your controller (since the controller is newed up and disposed with each request) or using dependency injection. You never want to create an instance of your context anywhere else, including an action method.

Only return selected fields in Web API results

First of all, this is not exactly a duplication of the dozens of other posts and I have tried all of them and none of them work.
I have a model that contains many more values than my web api consumers need.
public class Publication
{
[Key]
public int PublicationID { get; set; }
public string PublicationTitle { get; set; }
public string Frequency { get; set; }
public DateTime NextIssueDate { get; set; }
public DateTime SpaceDeadline { get; set; }
public DateTime MaterialsDeadline { get; set; }
public DateTime CreatedDt { get; set; }
public string CreatedBy { get; set; }
public DateTime UpdatedDt { get; set; }
public string UpdatedBy { get; set; }
}
I only want say a few of the fields to be passed in the API. I've tried this code but instead of leaving out say UpdateBy in the Json result, it returns it with a null value. How do I get rid of that? I've tried several dozen variations but they either fail to compile or fail to return results.
public IQueryable<Publication> GetPublications()
{
return db.Publications
.ToList()
.Select(p => new Publication {
PublicationID = p.PublicationID,
PublicationTitle = p.PublicationTitle,
Frequency = p.Frequency,
NextIssueDate = p.NextIssueDate
})
.AsQueryable();
}
Don't serialize your DAO. Create a complete contract and then serialize it selectively. To creating different contracts for different cases, you could simplify it using Json.Net; you could just create a custom contract resolver and use it as a parameter of SerializeObject() like so
static void Main(string[] args)
{
var person = new TestContract {FirstName = "John", LastName = "Doe", Age = 36};
var firstNameContract = new SelectiveSerializer("firstname");
var allPropertiesContract = new SelectiveSerializer("firstname, lastname, age");
var allJson = JsonConvert.SerializeObject(
person,
Formatting.Indented,
new JsonSerializerSettings {ContractResolver = allPropertiesContract});
var firstNameJson = JsonConvert.SerializeObject(
person,
Formatting.Indented,
new JsonSerializerSettings {ContractResolver = firstNameContract});
Console.WriteLine(allJson);
// {
// "FirstName": "John",
// "LastName": "Doe",
// "Age": 36
// }
Console.WriteLine(firstNameJson);
// {
// "FirstName": "John",
// }
}
public class SelectiveSerializer : DefaultContractResolver
{
private readonly string[] _fields;
public SelectiveSerializer(string fields)
{
var fieldColl = fields.Split(',');
_fields = fieldColl
.Select(f => f.ToLower().Trim())
.ToArray();
}
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
var property = base.CreateProperty(member, memberSerialization);
property.ShouldSerialize = o => _fields.Contains(member.Name.ToLower());
return property;
}
}
public class TestContract
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
}
Without much effort, you could probably work this into your default mediatype formatter (in the pipeline) to look for a parameter in the request called 'fields' or whatever and then use the custom contract resolver if present, and then it would be seamless default behavior to limit fields if specified or serialize the entire object if not specified.
On the academic side, here is the justification:
Any modification to the data is considered a "view concern" which means, in an API, it should controlled by query parameters and accept header. In this case, the "representation" of the data is application/json and you've chose to "filter" the returned fields. All of this can (and should be, imo) be handled during serialization. So your "model" in this case will always be the full model vs. some subset of the model. The full model in this example contains first name, last name, and age. In reality, this could be hundreds of properties. If you want to allow the client to choose a subset of the complete model, this is how you could do it with selective serialization.
You can similar behaviors in graph apis. There, the default for large models is that you get an empty object if you don't specify fields, forcing the client to be very specific about what it asks for, which is great when payload size matters (e.g. mobile applications). And, there's nothing stopping from creating field presets like 'name' which could mean 'firstname, lastname' or 'all' which includes all properties.
I've never been a fan of having hundreds of data objects that all serve some ad hoc requirement for a data set that is used in 20 different contexts where some cases require more data while others require less. IMO if you have to go through the same process to get the data, whether it complete or not, you shouldn't waste your time creating additional objects to frame the data for the sake of the client, and this should help you achieve that.
It's because you're returning a collection of Publication objects so you will get every property that is contained in that class, whether you populate it or not. If you want to return a subset of the properties then create a class that has only the properties you want to return and create an instance of that class in your query.
public IQueryable<WhatIReallyWantToReturn> GetPublications()
{
return db.Publications
.ToList()
.Select(p => new WhatIReallyWantToReturn {
PublicationID = p.PublicationID,
PublicationTitle = p.PublicationTitle,
Frequency = p.Frequency,
NextIssueDate = p.NextIssueDate
})
.AsQueryable();
}
private class WhatIReallyWantToReturn
{
public int PublicationID { get; set; }
public string PublicationTitle { get; set; }
public string Frequency { get; set; }
public DateTime NextIssueDate { get; set; }
}
using Newtonsoft.Json;
public class Publication
{
[Key]
public int PublicationID { get; set; }
public string PublicationTitle { get; set; }
public string Frequency { get; set; }
public DateTime NextIssueDate { get; set; }
public DateTime SpaceDeadline { get; set; }
public DateTime MaterialsDeadline { get; set; }
[JsonIgnore]
public DateTime CreatedDt { get; set; }
[JsonIgnore]
public string CreatedBy { get; set; }
[JsonIgnore]
public DateTime UpdatedDt { get; set; }
[JsonIgnore]
public string UpdatedBy { get; set; }
}
as Craig W. said you can use viewmodel ,also you can use anonymous type
(notice viewmodel is better way because you can use some utilities like automapper for mapping your property automatically)
JsonIgnore annotation has worked for me
[JsonIgnore]
public int Ranking { get; set; }
Here is a great article (Dec 2019) on the subject. It offers a solution for data shaping by making use of ExpandoObject and Type Reflection. The properties that the client requires can then be passed through the request as a query parameter (i.e. separated by a comma). The article also offers solution to the JSON Serialization problem.
Startup.cs file:
services.AddControllers(config =>
{
config.RespectBrowserAcceptHeader = true;
config.ReturnHttpNotAcceptable = true;
})
.AddXmlDataContractSerializerFormatters()
.AddNewtonsoftJson();
+1 for Sinaesthetic's answer.
I just finished reading an article, about GraphQL which solves exactly this problem. You can define exactly which fields do you need in the same request. No need for creating new endpoints every single time, when the caller needs just a specific subset of the properties.
If you can do this in .NET WEB API too without creating new models and endpoints, with just a very little extra effort, why wouldn't you (instead of exchanging Web Api for GraphQL).
Actually his SelectiveSerializer could be upgarded with reflection, so if you want to define which props you need in
C#, you can do this by providing property expressions, so you don't have to worry about misstyping prop names.
I bet there are other solutions for this, but the basic concept is the most important that we can define which fields we need in our json without creating new models.

List<T> caching, class iteration, count property

Hy,
I have created a custom List, which tried to cache, but when getting back from cache, the cached object count is 0. Example code below:
List<CategoryEntry> categs = (List<CategoryEntry>)EPiServer.CacheManager.Get("test");
if(categs == null || categs.Count == 0)
{
categs = ConstructCategories();
EPiServer.CacheManager.Add("test", categs);
}
//Further down displaying the categories
UseCase:
First Pageload (after build) cache is empty, categs will be null,
Second Pageload cache will be, but will fail from get from there becouse categs.Count will be 0 and reconstructs the cache again and again....
the CategoryEntry class:
[serializable]
public class CategoryEntry{
public string Title { get; set; }
public string URL { get; set; }
public int CategoryId { get; set; }
public int CompanyPageId { get; set; }
public int ParentCategoryEntryId { get; set; }
public int Indent { get; set; }
}
The problem should be when saving the cache bc. it is saved as object, and when we get the cache we Cast to List<CategoryEntry>.
Also figured out if i do this with a List<string> instead of using List<CategoryEntry>
then the caching works perfectly!.
Example with List<string> which is working:
List<string> test = (List<string>)EPiServer.CacheManager.Get("sindex");
if (test == null)
{
test = new List<string>();
test.Add("item1");
test.Add("item2");
test.Add("item3");
test.Add("item4");
test.Add("item5");
EPiServer.CacheManager.Add("sindex", test);
}
else
{
Response.Write("It works: elements "+ test.Count);
}
Another Tryout was that i have cached a simple instance of CategoryEntry and that also works, the problem is when i try to save as List<CategoryEntry>
Any help Would be apreciated, thank you.

Resources