I want to map MinerStatus from Entity.Miner.
I tried to include Miner entity in Issue entity, but it did not happen.
Service
Mapping profiles
I need to do it with AutoMapper, but it returns null.
This is my code:
Issue entity:
namespace Mining_Automation.Entities;
[Table("Issues")]
public class Issue : EntityBase, IAuditableEntity
{
public string? DescriptionForReportIssues { get; set; }
public string? ObjectsInMonitoringRoom { get; set; }
public bool? IsReadyToSendToFarm { get; set; }
public StatusInIssue? CurrentStatusInIssue { get; set; }
public long MinerId { get; set; }
public string Date { get; set; }
public string Time { get; set; } = TimeOnly.FromDateTime(DateTime.UtcNow).ToString();
public string? ProblemDescription { get; set; }
public string? Description { get; set; }
public string? TestRoomDescription { get; set; }
public string? RepairRoomDescription{ get; set; }
public string? RepairRoomIssueDescription { get; set; }
public Miner Miner { get; set; }
}
Miner entity:
namespace Mining_Automation.Entities;
[Table("Miners")]
public class Miner: EntityBase , IAuditableEntity
{
public string MinerName { get; set; }
public string AssetTag { get; set; }
public string MinerSerialNumber { get; set; }
public bool IsMinerActive { get; set; }
public long MinerStatus { get; set; }
public string WorkerName { get; set; }
public string? MinerDescription { get; set; }
public long FarmId { get; set; }
public Farm Farm { get; set; }
public ICollection<Issue> Issues{ get; set; }
public virtual MinerParts MinerParts { get; set; }
public ICollection<WatcherDataByMiner> WatcherDataByMiner { get; set; }
}
AllIssues view model:
namespace Mining_Automation.ViewModels.Issue;
public class ShowAllIssues
{
public long MinerId { get; set; }
public long IssueId { get; set; }
public string Date { get; set; }
public string WorkerName { get; set; }
public string MinerSerialNumber { get; set; }
public MinerStatus MinerStatus { get; set; }
public string DescriptionForReportIssues { get; set; }
public string ObjectsInMonitoringRoom { get; set; }
public bool IsReadyToSendToFarm { get; set; } = false;
public string ProblemDescription { get; set; }
public bool IsDeleted { get; set; }
public long Id { get; set; }
#endregion
}
Hi I am trying to deserialize this json. And my application does not do it for me.
i am using c#
any suggestion? thanks
this way i try to deserialize
var deserialize = resultado.Content.ReadAsStringAsync().Result;
var a = JsonConvert.DeserializeObject<product>(deserialize);
json received
{"product":{"id":6979552313549,"title":"Balance 100% Whey Protein 2.8kg w\/ FREE Magnesium complete powder","body_html":"Mountaineering backpack","vendor":"Balance","product_type":"physical","created_at":"2022-05-16T17:41:57-06:00","handle":"balance-100-whey-protein-2-8kg-w-free-magnesium-complete-powder-1","updated_at":"2022-05-26T12:34:07-06:00","published_at":"2022-05-16T17:41:57-06:00","template_suffix":null,"status":"active","published_scope":"web","tags":"Protein Powders, Specials, Stacks and Packs, Whey Protein Blend (WPI\/WPC)","admin_graphql_api_id":"gid:\/\/shopify\/Product\/6979552313549","variants":[{"id":40875072585933,"product_id":6979552313549,"title":"Default Title","price":"700.00","sku":"","position":1,"inventory_policy":"deny","compare_at_price":null,"fulfillment_service":"manual","inventory_management":"shopify","option1":"Default Title","option2":null,"option3":null,"created_at":"2022-05-26T12:34:07-06:00","updated_at":"2022-05-26T12:34:07-06:00","taxable":true,"barcode":null,"grams":0,"image_id":null,"weight":0.0,"weight_unit":"kg","inventory_item_id":42969806831821,"inventory_quantity":0,"old_inventory_quantity":0,"requires_shipping":true,"admin_graphql_api_id":"gid:\/\/shopify\/ProductVariant\/40875072585933"}],"options":[{"id":8937193341133,"product_id":6979552313549,"name":"Title","position":1,"values":["Default Title"]}],"images":[{"id":30230589407437,"product_id":6979552313549,"position":1,"created_at":"2022-05-26T12:34:07-06:00","updated_at":"2022-05-26T12:34:07-06:00","alt":null,"width":2862,"height":2143,"src":"https:\/\/cdn.shopify.com\/s\/files\/1\/0618\/4189\/9725\/products\/Definici_C3_B3n-del-producto-y-servicio_0bf23268-fee3-4b3b-a577-aeaa2336d6fc.png?v=1653590047","variant_ids":[],"admin_graphql_api_id":"gid:\/\/shopify\/ProductImage\/30230589407437"}],"image":{"id":30230589407437,"product_id":6979552313549,"position":1,"created_at":"2022-05-26T12:34:07-06:00","updated_at":"2022-05-26T12:34:07-06:00","alt":null,"width":2862,"height":2143,"src":"https:\/\/cdn.shopify.com\/s\/files\/1\/0618\/4189\/9725\/products\/Definici_C3_B3n-del-producto-y-servicio_0bf23268-fee3-4b3b-a577-aeaa2336d6fc.png?v=1653590047","variant_ids":[],"admin_graphql_api_id":"gid:\/\/shopify\/ProductImage\/30230589407437"}}}
If I have a Model class called "Product"
public class product
{
public long id { get; set; }
public string title { get; set; }
public string body_html { get; set; }
public string vendor { get; set; }
public string product_type { get; set; }
public DateTime created_at { get; set; }
public string handle { get; set; }
public DateTime updated_at { get; set; }
public DateTime published_at { get; set; }
public object template_suffix { get; set; }
public string status { get; set; }
public string published_scope { get; set; }
public string tags { get; set; }
public string admin_graphql_api_id { get; set; }
public List<Models.Producto.Variant> variants { get; set; }
public List<Models.Producto.Option> options { get; set; }
public List<Models.Producto.Images> images { get; set; }
public Models.Producto.Image image { get; set; }
}
I can see that you are using a wrong class to deserialize json, should be
var data=JsonConvert.DeserializeObject<Data>(json);
main classes (I highly recommend you to use a Pascal style for property names)
public partial class Data
{
[JsonProperty("product")]
public Product Product { get; set; }
}
public partial class Product
{
[JsonProperty("id")]
public long Id { get; set; }
[JsonProperty("title")]
public string Title { get; set; }
[JsonProperty("body_html")]
public string BodyHtml { get; set; }
[JsonProperty("vendor")]
public string Vendor { get; set; }
[JsonProperty("product_type")]
public string ProductType { get; set; }
[JsonProperty("created_at")]
public DateTimeOffset CreatedAt { get; set; }
[JsonProperty("handle")]
public string Handle { get; set; }
[JsonProperty("updated_at")]
public DateTimeOffset UpdatedAt { get; set; }
[JsonProperty("published_at")]
public DateTimeOffset PublishedAt { get; set; }
[JsonProperty("template_suffix")]
public object TemplateSuffix { get; set; }
[JsonProperty("status")]
public string Status { get; set; }
[JsonProperty("published_scope")]
public string PublishedScope { get; set; }
[JsonProperty("tags")]
public string Tags { get; set; }
[JsonProperty("admin_graphql_api_id")]
public string AdminGraphqlApiId { get; set; }
[JsonProperty("variants")]
public List<Variant> Variants { get; set; }
[JsonProperty("options")]
public List<Option> Options { get; set; }
[JsonProperty("images")]
public List<Image> Images { get; set; }
[JsonProperty("image")]
public Image Image { get; set; }
}
other classes
public partial class Image
{
[JsonProperty("id")]
public long Id { get; set; }
[JsonProperty("product_id")]
public long ProductId { get; set; }
[JsonProperty("position")]
public long Position { get; set; }
[JsonProperty("created_at")]
public DateTimeOffset CreatedAt { get; set; }
[JsonProperty("updated_at")]
public DateTimeOffset UpdatedAt { get; set; }
[JsonProperty("alt")]
public object Alt { get; set; }
[JsonProperty("width")]
public long Width { get; set; }
[JsonProperty("height")]
public long Height { get; set; }
[JsonProperty("src")]
public Uri Src { get; set; }
[JsonProperty("variant_ids")]
public List<object> VariantIds { get; set; }
[JsonProperty("admin_graphql_api_id")]
public string AdminGraphqlApiId { get; set; }
}
public partial class Option
{
[JsonProperty("id")]
public long Id { get; set; }
[JsonProperty("product_id")]
public long ProductId { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("position")]
public long Position { get; set; }
[JsonProperty("values")]
public List<string> Values { get; set; }
}
public partial class Variant
{
[JsonProperty("id")]
public long Id { get; set; }
[JsonProperty("product_id")]
public long ProductId { get; set; }
[JsonProperty("title")]
public string Title { get; set; }
[JsonProperty("price")]
public string Price { get; set; }
[JsonProperty("sku")]
public string Sku { get; set; }
[JsonProperty("position")]
public long Position { get; set; }
[JsonProperty("inventory_policy")]
public string InventoryPolicy { get; set; }
[JsonProperty("compare_at_price")]
public object CompareAtPrice { get; set; }
[JsonProperty("fulfillment_service")]
public string FulfillmentService { get; set; }
[JsonProperty("inventory_management")]
public string InventoryManagement { get; set; }
[JsonProperty("option1")]
public string Option1 { get; set; }
[JsonProperty("option2")]
public object Option2 { get; set; }
[JsonProperty("option3")]
public object Option3 { get; set; }
[JsonProperty("created_at")]
public DateTimeOffset CreatedAt { get; set; }
[JsonProperty("updated_at")]
public DateTimeOffset UpdatedAt { get; set; }
[JsonProperty("taxable")]
public bool Taxable { get; set; }
[JsonProperty("barcode")]
public object Barcode { get; set; }
[JsonProperty("grams")]
public long Grams { get; set; }
[JsonProperty("image_id")]
public object ImageId { get; set; }
[JsonProperty("weight")]
public long Weight { get; set; }
[JsonProperty("weight_unit")]
public string WeightUnit { get; set; }
[JsonProperty("inventory_item_id")]
public long InventoryItemId { get; set; }
[JsonProperty("inventory_quantity")]
public long InventoryQuantity { get; set; }
[JsonProperty("old_inventory_quantity")]
public long OldInventoryQuantity { get; set; }
[JsonProperty("requires_shipping")]
public bool RequiresShipping { get; set; }
[JsonProperty("admin_graphql_api_id")]
public string AdminGraphqlApiId { get; set; }
}
try this:
var response = JsonConvert.DeserializeObject<Dictionary<<string, string>>(deserialize);
string value = response["key"];
This is my model class.
In RootObject class I have a list of Trans class.In .net core when I am passing values to RootObject through Postman,I am getting null in RootObject.
public class Trans
{
public string SubDetailID { get; set; }
public string TrnType { get; set; }
public decimal amount { get; set; }
public string BankCurrencyRate { get; set; }
public decimal AccountID { get; set; }
public string Currency { set; get; }
public string CurrencyRate { set; get; }
public decimal JVID { get; set; }
public string coa { get; set; }
public decimal BusinessID { get; set; }
}
public class RootObject
{
public int JVID { get; set; }
public string InvoiceRef { get; set; }
public DateTime JVDate { get; set; }
public string StoreID { get; set; }
public decimal BusinessID { get; set; }
public string UserID { get; set; }
public string Currency { get; set; }
public string Rate { get; set; }
public DateTime DueDate { get; set; }
public string Reference { get; set; } = "Client";
public decimal RefID { get; set; }
public string Narration { get; set; }
public string Type { get; set; } = "CA";
public virtual List<Trans> transaction { get; set; }
}
I have some data from Facebook API and I need to store them on Azure SQL Db.
I created the models and I'm trying to set Foreign Keys to link the tables but I always have some errors.
My models:
public class FacebookDataUser
{
[Key]
[JsonProperty("id")]
public string FacebookDataUserId { get; set; }
public string name { get; set; }
public string birthday { get; set; }
public string email { get; set; }
public virtual Hometown hometown { get; set; }
public virtual Location location { get; set; }
public virtual Events events { get; set; }
public virtual Likes likes { get; set; }
public virtual Age_Range age_range { get; set; }
public string gender { get; set; }
}
public class Hometown
{
[Key]
[JsonProperty("id")]
public string HometownId { get; set; }
public string name { get; set; }
public string FacebookDataUserId { get; set; }
public FacebookDataUser FacebookDataUser { get; set; }
}
public class Location
{
[Key]
[JsonProperty("id")]
public string LocationId { get; set; }
public string name { get; set; }
public string FacebookDataUserId { get; set; }
public FacebookDataUser FacebookDataUser { get; set; }
}
public class Events
{
[Key]
public string EventsId { get; set; }
public Datum[] data { get; set; }
public string FacebookDataUserId { get; set; }
public FacebookDataUser FacebookDataUser { get; set; }
}
public class Datum
{
[Key]
public string DatumId { get; set; }
public string description { get; set; }
public string name { get; set; }
public DateTime start_time { get; set; }
public string PlaceId { get; set; }
public Place Place { get; set; }
public int attending_count { get; set; }
public string type { get; set; }
public string rsvp_status { get; set; }
public DateTime end_time { get; set; }
public string FacebookDataUserId { get; set; }
public FacebookDataUser FacebookDataUser { get; set; }
}
public class Place
{
[Key]
public string PlaceId { get; set; }
public string name { get; set; }
public string LocationEventId { get; set; }
public LocationEvent location { get; set; }
public string DatumId { get; set; }
public Datum Datum { get; set; }
}
public class LocationEvent
{
[Key]
public string LocationEventId { get; set; }
public string city { get; set; }
public string country { get; set; }
public float latitude { get; set; }
public float longitude { get; set; }
public string state { get; set; }
public string street { get; set; }
public string zip { get; set; }
public string FacebookDataUserId { get; set; }
public FacebookDataUser FacebookDataUser { get; set; }
}
public class Likes
{
// Doesn't have ID for Likes, but I need to have a Key in all classes.
// If I don't have, I get an exception
[Key]
public string LikesId { get; set; }
public Datum1[] data { get; set; }
public string FacebookDataUserId { get; set; }
public FacebookDataUser FacebookDataUser { get; set; }
}
public class Datum1
{
[Key]
public string Datum1Id { get; set; }
public string category { get; set; }
public string name { get; set; }
public int fan_count { get; set; }
public string website { get; set; }
public string LocationId { get; set; }
public LocationEvent location { get; set; }
public string[] emails { get; set; }
public string FacebookDataUserId { get; set; }
public FacebookDataUser FacebookDataUser { get; set; }
}
public class Age_Range
{
// Doesn't have ID for Age_Range, but I need to have a Key in all classes.
// If I don't have, I get an exception
[Key]
public string Age_RangeId { get; set; }
public int min { get; set; }
public string FacebookDataUserId { get; set; }
public FacebookDataUser FacebookDataUser { get; set; }
}
I get this exception:
Unable to determine the principal end of an association between the types 'ApiGroma.Models.Age_Range' and 'ApiGroma.Models.FacebookDataUser'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations.
If I add [Required] on Age_Range, I get this exception from Facebook API:
"modelState": {
"facebookDataUser.age_range.FacebookDataUser": [
"The FacebookDataUser field is required."
So, I tried to fill the values of Foreign Keys "by hand" before the method Add in my [HttpPost] method.
facebookDataUser.hometown.FacebookDataUserId = facebookDataUser.FacebookDataUserId;
facebookDataUser.location.FacebookDataUserId = facebookDataUser.FacebookDataUserId;
facebookDataUser.age_range.FacebookDataUserId = facebookDataUser.FacebookDataUserId;
facebookDataUser.likes.FacebookDataUserId = facebookDataUser.FacebookDataUserId;
facebookDataUser.events.FacebookDataUserId = facebookDataUser.FacebookDataUserId;
db.FacebookDataUsers.Add(facebookDataUser);
But I keep receiving the exception.
What's the proper way to do this?
It's been 2 days since I began looking for a solution, reading Microsoft blogs and others, but I can't fix this.
OBS: I am creating the database inside the context class.
Database.SetInitializer<MobileServiceContext>(new CreateDatabaseIfNotExists<MobileServiceContext>());
As I mentioned in the comments you must have your users into the database before inserting data to other tables related to those users (foreign keys).
Insert into table with foreign key
#EDIT: as promised, here is some code. I recommend you updating your table to accept null values in public virtual Hometown hometown { get; set; } and others.
public class FacebookDataUser
{
public string FacebookDataUserId { get; set; } // You already have the primary key you need
public string name { get; set; }
public string birthday { get; set; }
public string email { get; set; }
public virtual Hometown hometown { get; set; }
public virtual Location location { get; set; }
public virtual Events events { get; set; }
public virtual Likes likes { get; set; }
public virtual Age_Range age_range { get; set; }
public string gender { get; set; }
public void InsertUser(FacebookDataUser Data, Likes MoreData)
{
using (SqlConnection myCon = new SqlConnection("connection_string"))
{
using (SqlCommand query = new SqlCommand("INSERT INTO users_table (#ID, ...) VALUES (ID, ...)", myCon))
{
query.Parameters.AddWithValue("#ID", Data.FacebookDataUserId);
// add more parameters...
try
{
myCon.Open();
query.ExecuteNonQuery();
}
catch(Exception e)
{
throw e;
}
finally
{
myCon.Close();
}
}
using (SqlCommand query = new SqlCommand("INSERT INTO likes_table (..., #USERID) VALUES (..., USERID)", myCon))
{
// add more parameters...
query.Parameters.AddWithValue("#USERID", Data.FacebookDataUserId); // you won't get any exception related to the foreign key because this user is already in the parent table
try
{
myCon.Open();
query.ExecuteNonQuery();
}
catch (Exception e)
{
throw e;
}
finally
{
myCon.Close();
}
}
}
}
}
I didn't run a query to get the user ID as I mentioned because you already have it, just organizing the way you run your methods should be enough.
So, after some changes and compairing the codes, i got it working.
public class FacebookDataUser
{
[Key,JsonProperty("id")]
public string FacebookDataUserId { get; set; }
public string name { get; set; }
public string birthday { get; set; }
public string email { get; set; }
public virtual Hometown Hometown { get; set; }
public virtual Location Location { get; set; }
public virtual Events Events { get; set; }
public virtual Likes Likes { get; set; }
public virtual Age_Range Age_Range { get; set; }
public string gender { get; set; }
}
public class Hometown
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int HometownId { get; set; }
public string id { get; set; }
public string name { get; set; }
}
public class Location
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int LocationId { get; set; }
public string id { get; set; }
public string name { get; set; }
}
public class Events
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int EventsId { get; set; }
[JsonProperty("data")]
public ICollection<EventData> EventDatas { get; set; }
}
public class EventData
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int EventDataId { get; set; }
public string description { get; set; }
public string name { get; set; }
[Column(TypeName = "datetime2")]
public DateTime start_time { get; set; }
public virtual Place Place { get; set; }
public int attending_count { get; set; }
public string type { get; set; }
public string rsvp_status { get; set; }
[Column(TypeName = "datetime2")]
public DateTime end_time { get; set; }
}
public class Place
{
[Key,DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int PlaceId { get; set; }
public string id { get; set; }
public string name { get; set; }
[JsonProperty("location")]
public virtual LocationEvent LocationEvent { get; set; }
}
public class LocationEvent
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int LocationEventId { get; set; }
public string city { get; set; }
public string country { get; set; }
public float latitude { get; set; }
public float longitude { get; set; }
public string state { get; set; }
public string street { get; set; }
public string zip { get; set; }
}
public class Likes
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int LikesId { get; set; }
[JsonProperty("data")]
public virtual ICollection<LikesData> LikesData { get; set; }
}
public class LikesData
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int LikesDataId { get; set; }
public string id { get; set; }
public string category { get; set; }
public string name { get; set; }
public int fan_count { get; set; }
public string website { get; set; }
[JsonProperty("location")]
public virtual LocationEvent LocationEvent { get; set; }
[JsonProperty("emails")]
public virtual ICollection<string> emails { get; set; }
}
public class Age_Range
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Age_RangeId { get; set; }
public int min { get; set; }
}
my model classes first:
public class Person
{
[Required, Key]
public int ID { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string LearntSkillsAndLevelOfSkills { get; set; }
public string ProfileImage { get; set; }
public string City { get; set; }
public string PhoneNr { get; set; }
[Required]
public string Email { get; set; }
public string Hobbys { get; set; }
public string SkillsToLearn { get; set; }
public string Stand { get; set; }
public int YearsOfWorkExperience { get; set; }
public string HobbyProjectICTRelated { get; set; }
public string ExtraInfo { get; set; }
public string Summary { get; set; }
public int UserId { get; set; }
[ForeignKey("UserId")]
public virtual UserProfile profile { get; set; }
}
[Table("UserProfile")]
public class UserProfile
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string UserName { get; set; }
public Nullable<int> ID { get; set; }
public virtual Person personprofile { get; set; }
}
when i run this however it gives me this exception: The principal end of this association must be explicitly configured
i've searched this error but it doesn't clarify it for me... so i absolutely have no clue how to fix this. Basically i want to link my Person class to the Userprofiles so that i can create a login mechanism that automatically lets 1 person who makes an account on the site get 1 Profile to Edit to his own information. He's however not allowed to modify other people their accounts.
I hope this makes my problem clear and that somebody can help me :). i'm using EF 6 btw and i get the error in the class InitializeSimpleMembershipAttribute that comes standard with the MVC example of ASP.net
Greetings and thanks in advance,
Marijn
I managed to get it working with these codes in the models:
[Table("UserProfile")]
public class UserProfile
{
[Key, DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string UserName { get; set; }
public virtual Person personprofile { get; set; }
}
public class Person
{
[ForeignKey("profile"), Key]
public int UserId { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string LearntSkillsAndLevelOfSkills { get; set; }
public string ProfileImage { get; set; }
public string City { get; set; }
public string PhoneNr { get; set; }
[Required]
public string Email { get; set; }
public string Hobbys { get; set; }
public string SkillsToLearn { get; set; }
public string Stand { get; set; }
public int YearsOfWorkExperience { get; set; }
public string HobbyProjectICTRelated { get; set; }
public string ExtraInfo { get; set; }
public string Summary { get; set; }
public UserProfile profile { get; set; }
}