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

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; }
}

Related

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.

LiteDB null reference on insert

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);

ViewModel To Model Use ExpressMapper List<object> to List<Model> as Field

My Model Is :
public class Product
{
public int id { get; set; }
public string Name { get; set; }
public string Color { get; set; }
public ICollection<Tag> Tags { get; set; }
}
public class Tag
{
public int id { get; set; }
public string Name { get; set; }
public int ProductId { get; set; }
[ForeignKey("ProductId")]
public virtual Product Product { get; set; }
}
And View Model Is :
public class ProductViewModel
{
public int id { get; set; }
public string Name { get; set; }
public string Color { get; set; }
public List<string> Tags { get; set; }
}
im using ExpressMapper To Mapping.
could it be map productviewModel List Tags To public ICollection Tags?
You can register your mappings like that:
Mapper.RegisterCustom<Tag, string>((tag) => tag.Name);
Mapper.Register<Product, ProductViewModel>();
Mapper.Compile();
Here is working example: https://dotnetfiddle.net/2r7l4z

Automapper maps source to destination but dest values are always null

I'm new to automapper and I'm having a problem with it. In this case the automapper is used to map models(EntityFramework generated) to my own viewmodels. This is what happens, the sourcemodel with it's values is mapped to a destinationmodel but the dest values are always null. What's going on with the values?
Now what did I do:
I referenced the automapper to my project and bootstrapped the mappings.
public static void RegisterAutoMapperMappings()
{
Mapper.Initialize(x =>
{
// Add the mappingprofiles you configured below
x.AddProfile(new RegistrationViewModelProfile());
});
}
public static IMappingExpression<TSource, TDest> IgnoreAllUnmapped<TSource, TDest>(this IMappingExpression<TSource, TDest> expression)
{
expression.ForAllMembers(opt => opt.Ignore());
return expression;
}
public class RegistrationViewModelProfile : Profile
{
protected override void Configure()
{
CreateMap<RegistrationViewModel, contact>().IgnoreAllUnmapped();
CreateMap<contact, RegistrationViewModel>().IgnoreAllUnmapped();
CreateMap<RegistrationViewModel, emailaddress>().IgnoreAllUnmapped();
CreateMap<emailaddress, RegistrationViewModel>().IgnoreAllUnmapped();
CreateMap<RegistrationViewModel, password>().IgnoreAllUnmapped();
CreateMap<password, RegistrationViewModel>().IgnoreAllUnmapped();
//Always check if mapping is valid
Mapper.AssertConfigurationIsValid();
}
}
My viewmodel:
public class RegistrationViewModel
{
public HttpPostedFileBase file { get; set; }
public String EmailAddress { get; set; }
public String Password { get; set; }
public string contact_givenname { get; set; }
public string contact_surname_prefix { get; set; }
public string contact_surname { get; set; }
public string contact_gender { get; set; }
public string contact_country { get; set; }
public string contact_residence { get; set; }
public Nullable<DateTime> contact_birth_date{ get; set; }
public DateTime create_date { get; set; }
public ICollection<int> Contact_roles { get; set; }
public string Emailaddress_verificationkey { get; set; }
}
My model:
public partial class contact
{
public contact()
{
this.contact_connection_rel = new HashSet<contact_connection_rel>();
this.contact_emailaddress_password_rel = new HashSet<contact_emailaddress_password_rel>();
this.contact_emailaddress_rel = new HashSet<contact_emailaddress_rel>();
this.contact_service_role_rel = new HashSet<contact_service_role_rel>();
this.given_answer = new HashSet<given_answer>();
this.given_answer1 = new HashSet<given_answer>();
}
public int contact_id { get; set; }
public string contact_initials { get; set; }
public string contact_givenname { get; set; }
public string contact_surname_prefix { get; set; }
public string contact_surname { get; set; }
public string contact_nickname { get; set; }
public string contact_gender { get; set; }
public Nullable<System.DateTime> contact_birth_date { get; set; }
public string contact_country { get; set; }
public string contact_residence { get; set; }
public string contact_ssn { get; set; }
public Nullable<System.DateTime> create_date { get; set; }
public Nullable<System.DateTime> modify_date { get; set; }
public Nullable<System.DateTime> delete_date { get; set; }
public virtual ICollection<contact_connection_rel> contact_connection_rel { get; set; }
public virtual ICollection<contact_emailaddress_password_rel> contact_emailaddress_password_rel { get; set; }
public virtual ICollection<contact_emailaddress_rel> contact_emailaddress_rel { get; set; }
public virtual ICollection<contact_service_role_rel> contact_service_role_rel { get; set; }
public virtual ICollection<given_answer> given_answer { get; set; }
public virtual ICollection<given_answer> given_answer1 { get; set; }
}
And to test the configuration the following lines are used. The vars contain the destination objects but are always null:
contact c = new contact();
contact testC = unitOfWork.ContactRepository.Find(82);
var x = Mapper.Map<contact, RegistrationViewModel>(testC);
var y = Mapper.Map(regModel, c, typeof(RegistrationViewModel), typeof(contact));
var b = Mapper.DynamicMap<RegistrationViewModel, contact>(regModel);
var z = Mapper.Map<RegistrationViewModel, contact>(regModel, c);
var w = Mapper.Map<RegistrationViewModel, contact>(regModel);
expression.ForAllMembers(opt => opt.Ignore());
You're telling AutoMapper to ignore all properties, so nothing gets mapped.
If you just want to ignore non-matching properties, see this answer for one way, otherwise you're going to have to explicitly map each property between the objects.

Cannot implicitly convert type 'System.Collections.Generic.List to 'Models.CustomerViewModel'

I am trying to pass a list of data containing two objects that are contained in a custom interface,
My interface consists of
public interface ICustomersAndSitesRepository
{
IQueryable<CustomerSite> CustomerSites { get; }
IQueryable<Customer> Customers { get; }
IQueryable<ICustomersAndSitesRepository> CustomerAndSites { get; }
}
Then my repository i have this method
public IQueryable <ICustomersAndSitesRepository> CustomerAndSites
{
get { return CustomerAndSites; }
}
Then i have my viewmodel
public class CustomerSitesListViewModel
{
public IList<CustomerSite> CustomerSites { get; set; }
public PagingInfo PagingInfo { get; set; }
public CustomerViewModel Customers { get; set; }
}
And my controller action
public ViewResult List([DefaultValue(1)] int page)
{
var customersWithSitesToShow = customersAndSitesRepository.CustomerAndSites;
var viewModel = new CustomerSitesListViewModel
{
Customers = customersWithSitesToShow.Skip((page - 1) * PageSize).Take(PageSize).ToList(),
PagingInfo = new PagingInfo
{
CurrentPage = page,
ItemsPerPage = PageSize,
TotalItems = customersWithSitesToShow.Count()
}
};
return View(viewModel); //Passed to view as ViewData.Model (or simply model)
}
This line throws an error as im trying to pass the collection to my paging function thats expecting a list.
Customers = customersWithSitesToShow.Skip((page - 1) * PageSize).Take(PageSize).ToList(),
The error is
Cannot implicitly convert type 'System.Collections.Generic.List to 'Models.CustomerViewModel'
Is there a way to convert the list that is being returned so that it can be used in the viewmodel?
This is the customer view model
public class CustomerViewModel
{
public int Id { get; set; }
public string CustomerName { get; set; }
public string PrimaryContactName { get; set; }
public string PrimaryContactNo { get; set; }
public string PrimaryEmailAddress { get; set; }
public string SecondaryContactName { get; set; }
public string SecondaryContactNo { get; set; }
public string SecondaryEmailAddress { get; set; }
public DateTime RegisteredDate { get; set; }
public string WasteCarrierRef { get; set; }
public string UnitNo { get; set; }
public string StreetName { get; set; }
public string Town { get; set; }
public string County { get; set; }
public string Postcode { get; set; }
public byte[] ImageData { get; set; }
public string ImageMimeType { get; set; }
public SiteViewModel Site { get; set; }
}
As the error says: the property CustomerSitesListViewModel.Customers is of type CustomerViewModel, but you are trying to assign a List<CustomerSite>.
Did you mean this instead:
CustomerSites = customersWithSitesToShow
.Skip((page - 1) * PageSize)
.Take(PageSize)
.ToList()
or maybe this:
Customers = new CustomerViewModel(customersWithSitesToShow...),