Unable to find a default constructor to use for type Microsoft.AspNetCore.Mvc.ViewFeatures.Internal.DynamicViewData - json.net

I am getting this error when trying to Deserialize the string from the redis cache using Newtonsoft.Json.
where HeaderTopViewComponent is model class of one of my view component ""
like: JsonConvert.DeserializeObject<HeaderTopViewComponent>(cacheValue.Result.ToString());
Unable to find a default constructor to use for type Microsoft.AspNetCore.Mvc.ViewFeatures.Internal.DynamicViewData. Path 'ViewBag', line 1, position 340.
Output string :
{"ShowTopheaderSection":true,"PageHeader":"MSHSL","FriendlyURL":"/MSHSL","leagueList":[{"leagueId":0,"FriendlyURL":"/","leaguename":"--Select--"},{"leagueId":3,"FriendlyURL":"/MSHSL","leaguename":"MSHSL"},{"leagueId":4,"FriendlyURL":"/CHSAA","leaguename":"CHSAA"}],"HttpContext":null,"Request":null,"User":null,"RouteData":null,"ViewBag":{},"ModelState":{},"Url":null,"ViewComponentContext":{"Arguments":null,"HtmlEncoder":null,"ViewComponentDescriptor":{"DisplayName":null,"FullName":null,"Id":"9882d08a-1c50-4c59-8a30-2d9c843957e9","ShortName":null,"TypeInfo":null,"MethodInfo":null},"ViewContext":{"FormContext":null,"ClientValidationEnabled":false,"Html5DateRenderingMode":0,"ValidationSummaryMessageElement":null,"ValidationMessageElement":null,"ViewBag":{},"View":null,"ViewData":{},"TempData":null,"Writer":null,"ExecutingFilePath":null,"ActionDescriptor":null,"HttpContext":null,"ModelState":{},"RouteData":null},"ViewData":{},"Writer":null},"ViewContext":{"FormContext":null,"ClientValidationEnabled":false,"Html5DateRenderingMode":0,"ValidationSummaryMessageElement":null,"ValidationMessageElement":null,"ViewBag":{},"View":null,"ViewData":{},"TempData":null,"Writer":null,"ExecutingFilePath":null,"ActionDescriptor":null,"HttpContext":null,"ModelState":{},"RouteData":null},"ViewData":{},"ViewEngine":null}

I have fix it by adding some tag in my viewcomponent modal class and get set property like
[JsonObject(MemberSerialization.OptIn)] and [JsonProperty]
//Tag to add only selected property when Deserialize or Serialize using Newtonsoft
[JsonObject(MemberSerialization.OptIn)]
public class HeaderTopViewComponent:ViewComponent
{
#region //Property//
[JsonProperty]
public bool ShowTopheaderSection { get; set; }
[JsonProperty]
public string PageHeader { get; set; }
[JsonProperty]
public string FriendlyURL { get; set; }
[JsonProperty]
And now its working

Related

I have one entity, i need to add property of entity type

**public class Ticket : BaseEntity
{
public TicketType TicketType { get; set; }
}
public class TicketType : AuxiliaryInfoBaseEntity
{
public string Description { get; set; }
}**
In Ticket Entity i need one property of TicketType and type of column should be byte in Ticket.
Resulting table will look like.Table-Ticket:column TicketType(tinyint,not null).
When i trying to migrate, i am getting this exception.
System.InvalidOperationException: 'The property 'Ticket.TicketType' is of type 'TicketType' which is not supported by current database provider. Either change the property CLR type or ignore the property using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'.
Please help me with some soluntion thanks.

Using OData how can I sort a property that holds a list?

Here is the problem I need to solve:
I need to display a grid that contains a group of columns that are dynamic, meaning that the number can change depending on the user parameters.
I have attached a sample below as an image to illustrate:
GRID SAME IMAGE
I have these c# POCOs to keep my question simple
public class OrderItem
{
public string ProductName { get; set; }
public string Status { get; set; }
public List<CityOrderInfo> CityOrders { get; set; }
}
public class CityOrderInfo
{
public int OrderCount { get; set; }
}
I have a web api controller that is able to accept the OData request, plus other arguments that the repository accepts. However the problem is that while the parameter $orderby for ProductName and Status works, when I do "$orderby='CityOrders[1]\OrderCount asc' it fails.
public class OrdersControllers : ApiController
{
private readonly IOrdersRepository _repository;
public OrdersControllers(IOrdersRepository repository)
{
this._repository = repository;
}
public IEnumerable<OrderItem> GetOrderItems([FromUri] ODataQueryOptions<OrderItem> oDataQuery)
{
var result = this._repository.GetOrders().ToList();
var queryableData = oDataQuery.ApplyTo(result.AsQueryable());
var transformedData = queryableData as IEnumerable<OrderItem>;
return transformedData;
}
}
The reason I opted to hold the city orders in list is because I thought it would too painful to make a POCO with every city in the USA as a property so instead made it more generic.
The question is how can a sort on a property that holds a list using OData? Is this possible? I keep getting syntax error at position n. As of now I have not found an answer.

Webapi. Define default Json value when enum property is missing

I have a webapi that accepts Post as followed (example)
public Foo Post(MyInfo info)
{
return new Foo();
}
MyInfo could be something like this
public class MyInfo
{
[JsonProperty(PropertyName = "n")]
public int MyInt1{ get; set; }
[JsonProperty(PropertyName = "v")]
public string MyString1{ get; set; }
}
Everything works fine when my desktop application (version 1) post a request to this webapi. I serialize the object with a JsonConverter.
Now let's say, I want to add a new parameter to MyInfo as followed
public class MyInfo
{
[JsonProperty(PropertyName = "n")]
public int MyInt1{ get; set; }
[JsonProperty(PropertyName = "v")]
public string MyString1{ get; set; }
[JsonProperty(PropertyName = "s")]
public MyEnum EnumValue{ get; set; }
}
I update the website and the webapi and I publish a new version of my desktop application (version 2).
The webapi works fine with the version 2 of my desktop application. However, when I use my version 1, the parameter (MyInfo info) in the webapi ends null.
As a reminder, the version 1 sends the exact same MyInfo object except that one property is missing.
How can I avoid this problem and define a default value if the property is missing.
Thanks
Well in fact the problem was that I had two properties with the same Json property name.
It was completly unrelated to the default value.

Is there a way to specify .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None) as a decorator to my entity?

I have the following class. I was using a mapping file but I would not like to decorate the class with the different options. I already have in my mapping file:
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
How can I set this or set another option of DatabaseGeneratedOption by decorating the class? I looked at the Intellisense options but can't find one for this all I can find is [DatabaseGenerated()] and I am not sure if that's correct or how to set that option:
[DatabaseGenerated()]
public class ContentType : Entity
{
public ContentType()
{
this.Contents = new List<Content>();
}
[Key]
public int ContentTypeId { get; set; }
public string Name { get; set; }
public virtual ICollection<Content> Contents { get; set; }
}
DatabaseGenerated is Property and Field specific attribute. You can't add it to a class, only specific properties or fields.

ASP.NET MVC3 EF model Inheritance Cannot implicitly convert type

I am sure i am just missing some pretty basic here, but i can't seem to figur it out.. maybe because its been a while since i have been on the .NET platform.
Anyway, I have this database structure i the ASP.NET MVC3 framework where i have "Coruse", "Tool" and "ToolADL"(Inheritance from Tool). A "Course" can have one-or-more "Tools" where one of the "Tool"-types is "ToolADL".
Models/Course.cs:
public class Course {
[Key]
public int CourseID { get; set; }
[Required(ErrorMessage = "{0} er påkrævet")]
[Display(Name = "Værktøj")]
public virtual ICollection<Tool> Tools { get; set; }
}
Models/Tool.cs:
public abstract class Tool {
public Tool(){
Priority = 0;
}
[Key]
public int ToolID { get; set; }
[Required]
public int CourseID { get; set; }
[Required]
public int Priority { get; set; }
}
Models/ToolADL.cs:
public class ToolADL : Tool {
[Required]
public string Image { get; set; }
}
aaand the Models/ProjectContext:
public class ProjectContext : DbContext {
// Course context
public DbSet<Course> Courses { get; set; }
// Tools
public DbSet<Tool> Tools { get; set; }
// ToolADL
public DbSet<ToolADL> ToolADLs { get; set; }
}
Now when i try to create the controller and connect to DbContext and the Model to it so the entity framwork can do its magic, I get the following error in the ToolADL controller Details function (and others) where time i use "find()":
ToolADLController.Details(int):
private ProjectContext db = new ProjectContext();
public ViewResult Details(int id){
ToolADL tooladl = db.Tools.Find(id);
return View(tooladl);
}
Error 1 Cannot implicitly convert type 'Project.Models.Tool'
to 'caREhab_community.Models.ToolADL'. An explicit conversion exists
(are you missing a cast?) C:\Users\Thor\Documents\Visual Studio
2010\Projects\Project\Project\Project\ToolADLController.cs 29 31 Project
(I changed the name of the orginal project to "Project")
I simply cannot figur out what I am doing wrong, Is it wrong types, some really basic about Inheritance i left out or something else?
Hope some kind soul can tell me why I am an idiot and can't figure this out :)
If object that is returned by db.Tools.Find(id) is of type ToolADL then you should do:
ToolADL tooladl = db.Tools.Find(id) as ToolADL;
After that You'll have your object or null.
If it's not of type ToolADL then you can't do this because:
When You have:
public class A { }
public class B : A { }
You can not do something like this:
A a = new A();
B b = a;
This is in fact a basic truth about inheritance.
You might change this implicit conversion to explicit on by doing:
B b = (B)a;
Then your code would compile but You would get a runtime exception:
Unable to cast object of type 'A' to type 'B'.
To make it work You would have to specify an explicit conversion like this:
public class A
{
public static explicit operator B(A a)
{
return new B();
}
}
But this will give you yet another compile time error:
'A.explicit operator B(A)': user-defined conversions to or from a
derived class are not allowed

Resources