LiteDB null reference on insert - litedb

I ran into this problem where in I get a null reference exception on insert.
I have two object Models UserInfo and UserConfig. On the first trial, UserConfig references a UserInfo instance
public class UserConfigObject : IUserConfig
{
BsonRef("userInfo")]
public IUserInfo UserInfo { get; set; }
public string AssignedJob { get; set; }
public string[] QueueItems { get; set; }
}
public class UserInfoObject : IUserInfo
{
[BsonId]
public int ID { get; set; }
public string Name { get; set; }
public string Username { get; set; }
public string IPAddress { get; set; }
}
And a method to insert the data into the database
public void AddUser(IUserConfig user)
{
var uconCollection = DatabaseInstance.GetCollection<IUserConfig>("userConfig");
var uinCollection = DatabaseInstance.GetCollection<IUserInfo>("userInfo");
uinCollection.Insert(user.UserInfo);
uconCollection.Insert(user);
}
This set up works fine but when I try to change the reference to UserInfo references UserConfig
public class UserInfoObject : IUserInfo
{
[BsonId]
public int ID { get; set; }
public string Name { get; set; }
public string Username { get; set; }
public string IPAddress { get; set; }
[BsonRef("userConfig")]
public IUserConfig UserConfig { get; set; }
}
public class UserConfigObject : IUserConfig
{
[BsonRef("userInfo")]
public IUserInfo UserInfo { get; set; }
[BsonId(true)]
public int ConfigID { get; set; }
public string AssignedJob { get; set; }
public string[] QueueItems { get; set; }
}
With a method call for
public void AddUser(IUserInfo user)
{
var uconCollection = DatabaseInstance.GetCollection<IUserConfig>("userConfig");
var uinCollection = DatabaseInstance.GetCollection<IUserInfo>("userInfo");
uconCollection.Insert(user.UserConfig);
uinCollection.Insert(user);
}
It no longer works, it throws an System.NullReferenceException: 'Object reference not set to an instance of an object.' on uinCollection.Insert(user);
Either v3 or v4, it doesn't work with the latter set up

Had the same problem but with collections. I've tried to save collection of invitations like so:
using var db = new LiteRepository(_connectionString);
var invitations = new List<Invitation>
{
// populate list
};
db.Insert(invitations);
The problem is that T parameter resolved as IEnumerable<Invitation> not just Invitation, so if you are inserting a collection, set type explicitly.
db.Insert<Invitation>(invitations);

Related

Error "The JSON value could not be converted to System.String. Path: $[1].Interests[1].Meta[9].Content | LineNumber: 0 | BytePositionInLine: 10073."

public Class Employee{
public string Name { get; set; }
[Column(TypeName = "jsonb")]
public List<Section> Sections { get; set; }
}
public Class Sections{
public string Booking { get; set; }
[Column(TypeName = "jsonb")]
public List<Interest> Interests { get; set; }
}
public Class Interest{
public string Title { get; set; }
public List<Meta> Meta { get; set; }
public List<WithAlt> Images { get; set; }
}
public Class Meta{
public string Type { get; set; }
public string Content { get; set; }
}
public Class WithAlt{
public string content { get; set; }
public string Alt { get; set; }
}
I fetch data from the Employee table
Employee while fetching the data Sections Column I got
The JSON value could not be converted to System.String. Path: $[1].Interests[1].Meta[9].Content | LineNumber: 0 | BytePositionInLine: 10073.
Error at
public Task<Employee> CheckEmployee(string name){
// error throw Line
var query= await catalogDbContext.Employee
.Where(i.Name === name)
.FirstOrDefault();
}
Not for all value but some value that List<Section> or
List<Interest> or List<Meta> or List<WithAlt> have null value
When I manually add the value to sections column bellow
{
"Booking": "",
"Interests":[
{
"Title":"",
"Meta":[
{
"Type" : " ",
"Content" : " "
}
],
"Images" : [
{
"content" : " ",
"alt" : " "
}
]
}
],
}
it will not throw the error
Are there any way to define the default value to the above fields using code first approach
when I initialize Sections property like
public List<Section> Sections { get; set; }={};
it shows the following error
Can only use array initializer expressions to assign to array types. Try using a new expression instead.
and also
public List<Section> Sections { get; set; }= new List<Section> Sections();
and
public List<Meta> Meta { get; set; }= = new List<Meta>();
and
public List<WithAlt> Images { get; set; }= new List<WithAlt>();
throw Error "The JSON value could not be converted to System.String. Path: $[1].Interests[1].Meta[9].Content | LineNumber: 0 | BytePositionInLine: 10073."
Can only use array initializer expressions to assign to array types. Try using a new expression instead.
You can convert the json data to Section type rather than List<Section> type.
var json = "{\"Booking\":\"\",\"Interests\":[{\"Title\":\"\",\"Meta\":[{\"Type\":\" \",\"Content\":\" \"}],\"Images\":[{\"content\":\" \",\"alt\":\" \"}]}]}";
var s = JsonConvert.DeserializeObject<Section>(json);
//If you want to set Employee.Sections with json data,try this
Employee e = new Employee { Sections = new List<Section> { s } };
Models(change class name Sections to Section,Interests to Interest):
public class Employee
{
public string Name { get; set; }
[Column(TypeName = "jsonb")]
public List<Section> Sections { get; set; }
}
public class Section
{
public string Booking { get; set; }
[Column(TypeName = "jsonb")]
public List<Interest> Interests { get; set; }
}
public class Interest
{
public string Title { get; set; }
public List<Meta> Meta { get; set; }
public List<WithAlt> Images { get; set; }
}
public class Meta
{
public string Type { get; set; }
public string Content { get; set; }
}
public class WithAlt
{
public string content { get; set; }
public string Alt { get; set; }
}
I just deserialiazed you json , everything is working properly, I couldn' t find any errros
public static void Main()
{
var json = "{\"Booking\":\"\",\"Interests\":[{\"Title\":\"\",\"Meta\":[{\"Type\":\" \",\"Content\":\" \"}],\"Images\":[{\"content\":\" \",\"alt\":\" \"}]}]}";
var jd = JsonConvert.DeserializeObject<Data>(json);
}
classes
public class Data
{
public string Booking { get; set; }
public List<Interest> Interests { get; set; }
}
public class Interest
{
public string Title { get; set; }
public List<Meta> Meta { get; set; }
public List<Image> Images { get; set; }
}
public class Meta
{
public string Type { get; set; }
public string Content { get; set; }
}
public class Image
{
public string content { get; set; }
public string alt { get; set; }
}

Could not find the implementation of the query pattern for source type. Join not found

I don't know if I am doing this right. I have 2 tables Property and PropertyTypes. Each Property has 1 PropertyType. I am using a foreign key constraint. But on the creation of the controller, I get this error already:
"Could not find an implementation of the query pattern for source type 'DbSet'.'Join not found'
Please see my code below:
[Table("Property.Property")]
public class Property
{
[Key]
public int PropertyId { get; set; }
[StringLength(50)]
public string PropertyName { get; set; }
public int? Owner { get; set; }
public string Cluster { get; set; }
public string PropertyNumber { get; set; }
public string RegionCode { get; set; }
public string ProvinceCode { get; set; }
public string MunicipalCode { get; set; }
public string BarangayCode { get; set; }
public DateTime? DateAdded { get; set; }
public DateTime? DateModified { get; set; }
public int PropertyTypeId { get; set; }
public PropertyType PropertyType { get; set; }
[NotMapped]
public string Type { get; set; }
}
[Table("Property.Types")]
public class PropertyType
{
[Key]
public int PropertyTypeId { get; set; }
[StringLength(50)]
public string Type { get; set; }
public DateTime? DateAdded { get; set; }
public DateTime? DateModified { get; set; }
public List<Property> Properties { get; set; }
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection", throwIfV1Schema: false) {}
// DB Sets
public DbSet<Property> Properties { get; set; }
public DbSet<PropertyType> PropertyTypes { get; set; }
}
Controller
public class PropertyController : ApiController
{
[HttpGet]
[Authorize]
[Route("api/getproperties")]
public async Task<List<Property>> GetProperties()
{
using(var db = new ApplicationDbContext())
{
var properties = await (from p in db.Properties
join pt in db.PropertyTypes
on p.PropertyTypeId equals pt.PropertyTypeId
select new
{
PropertyId = p.PropertyId,
PropertyName = p.PropertyName,
Owner = p.ProertyOwner,
Cluster = p.Cluster,
PropertyNumber = p.PropertyNumber,
RegionCode = p.RegionCode,
ProvinceCode = p.ProvinceCode,
MunicipalCode = p.MunicipalCode,
BarangayCode = p.BarangayCode,
DateAdded = p.DateAdded,
DateModified = p.DateModified,
PropertyTypeId = p.PropertyTypeId,
type = pt.Type
}
).ToListAsync();
return properties;
}
}
}
Can you please show me the right way to do this? Thank you.

How to have a nested DTO?

I have this as my entity object:
public partial class RFID_Zones
{
public RFID_Zones()
{
this.RFID_ZonePoints = new HashSet<RFID_ZonePoints>();
}
public int PK_ZoneId { get; set; }
public int PK_FK_ShipId { get; set; }
public string ZoneName { get; set; }
public string Color { get; set; }
public virtual Ship Ship { get; set; }
public virtual ICollection<RFID_ZonePoints> RFID_ZonePoints { get; set;}
}
I am trying to pull all these with this code:
result = _db.RFID_Zones.Where(x => x.PK_FK_ShipId == shipId).Include(x => x.RFID_ZonePoints).ToList();
This works, but I cannot serialize it without getting a circular reference error. Upon Googling I find I should use a Data Transfer Object so I have this:
public class ZoneDto
{
public ZoneDto()
{
this.Zones = new List<RFID_ZonePoints>();
}
public int PK_ZoneId { get; set; }
public int PK_FK_ShipId { get; set; }
public string ZoneName { get; set; }
public string Color { get; set; }
public List<RFID_ZonePoints> Zones { get; set; }
}
And:
var dto = zones.Select(x => new ZoneDto { PK_ZoneId = x.PK_ZoneId, PK_FK_ShipId = x.PK_FK_ShipId,
Color = x.Color, ZoneName = x.ZoneName, Zones = x.RFID_ZonePoints.ToList()});
I still have the issue of the RFID_ZonePoints list. It's a list of a different entity. How can I get those into a data transfer object as well?

BreezeJs: Update to new metadata from changed BreezeController

I've changed and added some properties to my server-side classes but can't get the updated data in my breeze/angular app. The added fields stay blank instead of showing the value. I also can't create an entity that i've added. (error). How can i update the metadata in my breeze/angular app to use the latest version? I've tried to fetch the metadata, but getting the message that it already was fetched.
Breeze: Unable to locate a 'Type' by the name: 'New Class'. Be sure to execute a query or call fetchMetadata first
Update (More Info)
I've created a child class related to my Product class. It's called ProductStockItem, so a Product has many ProductStockItems.
ProductStockItem: (new Class)
public class ProductStockItem
{
public int Id { get; set; }
public int ProductId { get; set; }
public string Size { get; set; }
public int Quantity { get; set; }
public bool UseStockQuantity { get; set; }
public decimal PriceAdjustment { get; set; }
public DateTime? DateAvailable { get; set; }
public int DisplayOrder { get; set; }
public bool Deleted { get; set; }
public State State { get; set; }
public DateTime? DateChanged { get; set; }
public DateTime? DateCreated { get; set; }
public virtual Product Product { get; set; }
}
Product:
public class Product
{
private ICollection<ProductCategory> _productCategories;
private ICollection<ProductManufacturer> _productManufacturers;
private ICollection<ProductPicture> _productPictures;
private ICollection<ProductSpecificationAttribute> _productSpecificationAttributes;
private ICollection<ProductStockItem> _productStockItems;
public int Id { get; set; }
public ProductType ProductType { get; set; }
public int ParentGroupedProductId { get; set; }
public int ManufacturerSizeId { get; set; }
public bool VisibleIndividually { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string MetaTitle { get; set; }
public string MetaDescription { get; set; }
public int DisplayOrder { get; set; }
public bool LimitedToStores { get; set; }
public string Sku { get; set; }
public string UniqueCode { get; set; }
public decimal Price { get; set; }
public decimal OldPrice { get; set; }
public decimal? SpecialPrice { get; set; }
public DateTime? SpecialPriceStartDateTimeUtc { get; set; }
public DateTime? SpecialPriceEndDateTimeUtc { get; set; }
public decimal DiscountPercentage { get; set; }
public bool HasTierPrices { get; set; }
public bool HasStock { get; set; }
public TaxRate TaxRate { get; set; }
public bool SyncToShop { get; set; }
public bool Deleted { get; set; }
public bool Locked { get; set; }
public State State { get; set; }
public DateTime? DateChanged { get; set; }
public DateTime? DateCreated { get; set; }
public virtual ICollection<ProductCategory> ProductCategories
{
get { return _productCategories ?? (_productCategories = new List<ProductCategory>()); }
protected set { _productCategories = value; }
}
public virtual ICollection<ProductManufacturer> ProductManufacturers
{
get { return _productManufacturers ?? (_productManufacturers = new List<ProductManufacturer>()); }
protected set { _productManufacturers = value; }
}
public virtual ICollection<ProductPicture> ProductPictures
{
get { return _productPictures ?? (_productPictures = new List<ProductPicture>()); }
protected set { _productPictures = value; }
}
public virtual ICollection<ProductSpecificationAttribute> ProductSpecificationAttributes
{
get { return _productSpecificationAttributes ?? (_productSpecificationAttributes = new List<ProductSpecificationAttribute>()); }
protected set { _productSpecificationAttributes = value; }
}
public virtual ICollection<ProductStockItem> ProductStockItems
{
get { return _productStockItems ?? (_productStockItems = new List<ProductStockItem>()); }
protected set { _productStockItems = value; }
}
}
Product request:
http://testdomain.local/breeze/DataContext/Products?$filter=Id%20eq%201029&$orderby=Id&$expand=ProductStockItems&
[{"$id":"1","$type":"Erp.Models.ErpModel.Catalog.Product, Erp.Models.ErpModel","Id":1029,"ProductType":"SimpleProduct","ParentGroupedProductId":0,"ManufacturerSizeId":2767,"VisibleIndividually":false,"Name":"Jako Ballenzak Kids - Ash / Action Green","ExtraName":null,"Description":"• Aangenaam functioneel materiaal\nmet moderne oppervlaktestructuur\nvoor de hoogste normen\n• Zeer goede klimaateigenschappen\ndoor actief ademend Twill-Polyester\n• Rekbaar, vormvast en sneldrogend\n\nPolyester-Twill\n100% Polyester,\nbinnenvoering: 100% Polyester","MetaTitle":null,"MetaDescription":null,"DisplayOrder":1,"LimitedToStores":false,"Sku":"9894","UniqueCode":"6_9","Price":34.96,"OldPrice":49.95,"SpecialPrice":null,"SpecialPriceStartDateTime":null,"SpecialPriceEndDateTime":null,"DiscountPercentage":0.00,"HasTierPrices":true,"HasStock":false,"TaxRate":"Tax_21","SyncToShop":true,"Deleted":false,"Locked":false,"State":"Changed","DateChanged":"2014-02-28T10:35:47.733","DateCreated":"2014-02-28T10:35:47.733","ProductCategories":[],"ProductManufacturers":[],"ProductPictures":[],"ProductSpecificationAttributes":[],"ProductStockItems":[]}]
Metadata request:
http://testdomain.local/breeze/DataContext/Metadata
Error Client Side: (create new productStockItem)
Unable to locate a 'Type' by the name: 'ProductStockItem'. Be sure to execute a query or call fetchMetadata first.
function createProductStockItem(initialValues) {
return this.manager.createEntity("ProductStockItem", initialValues);
}
When you rebuild your application, the metadata will get updated. No extra job needed for making the
metadata to get fetched with it's updated state.
Whenever you issue a query on an entity that is included inside the metadata, the updated metadata
will get fetched.
For creating an entity, if you navigate directly to the page of creating an entity prior to any page that includes a query, the metadata won't get fetched in this case.
When you called fetchMetadata(), you still get the error:
Unable to locate a 'Type' by the name: 'New Class'. Be sure to execute a query or call `fetchMetadata` first
That message doesn't indicate that the metadata already was fetched. It still tells you that the entity is unknown and the metadata still not fetched.
Why? Because createEntity() was called before fetchMetadata(). (you can set a break-point and see that in action)
I ran into this before, and what I did, I simply put the fetchMetadata() on application launch.
That will guarantee that it will get fetched first before any call to creating an entity.
Or you can just use a promise:
manager.fetchMetadata().then(createProductStockItem("Initial values"));

I get UpdateException when i try to Update a collection property

I am in an MVC4 application and i am using EF CodeFirst.
When I try to run the following code:
public void Autorizare(int cerereId, Persoana persoana)
{
var cerere = _db.Cereri.Find(cerereId);
cerere.Autorizare.Add(persoana);
_db.SaveChanges();
}
I get an error like this:
Entities in 'CerereDbContext.Persoane' participate in the 'Actiune_Executanti' relationship. 0 related 'Actiune_Executanti_Source' were found. 1 'Actiune_Executanti_Source' is expected.
i have tried Entity(Actiune).State = EntityState.Modified, but no results.
I have a main POCO:
public class Cerere
{
public int Id { get; set; }
...
public virtual ICollection<Actiune> Actiuni { get; set; }
...
}
the Actiune class looks like this
public class Actiune
{
public int Id { get; set; }
public DateTime Data { get; set; }
public String Nume { get; set; }
public virtual ICollection<Persoana> Executanti { get; set; }
public String Stadiu { get; set; }
public String Obs { get; set; }
}
And Persoana:
public class Persoana
{
public int Id { get; set; }
public DateTime Data { get; set; }
public String Nume { get; set; }
}
From your model the Cerere does not have a property named Autorizare; however it does have one named Actiuni. Which is of type Actiune not Persoana which is what you are trying to add to it. Please post the rest of the Class Definition.