One to one relationship Mysql EF6 - mysql

Hi there I've been banging my head now for two days and haven't been able to solve this one: I have this data structure:
[
{
"LocalObservationDateTime": "2019-12-12T19:50:00+02:00",
"EpochTime": 1576173000,
"WeatherText": "Thunderstorm",
"WeatherIcon": 15,
"HasPrecipitation": true,
"Reciprocation": "Rain",
"IsDayTime": false,
"Temperature": {
"Metric": {
"Value": 13.7,
"Unit": "C",
"UnitType": 17
},
"Imperial": {
"Value": 57,
"Unit": "F",
"UnitType": 18
}
}
}
]
I designed my data like this:
Table1:
Id,
LocalObservationDateTime,
EpochTime
WeatherText,
WeatherIcon,
HasPrecipitation,
PrecipitationType,
IsDayTime,
TemperatureId
Table2
TemperatureId,
ImperialId,
MetricId
Table3
Id,
Value,
Unit,
UnitType
I connected FKs tables 3 Id ImperialId and MetricId in Table 3 and TemperatureId in Table 2 to TemperatureId in table1
these are my models:
[Table("currentweather")]
public class CurrentWeather
{
[Key, Column("id")]
public int Id { get; set; }
[Column("locationid")]
public int LocationId { get; set; }
[Column("localobservationdatetime")]
public DateTime LocalObservationDateTime { get; set; }
[Column("epochtime")]
public long EpochTime { get; set; }
[Column("weathertext")]
public string WeatherText { get; set; }
[Column("weathericon")]
public int WeatherIcon { get; set; }
[Column("hasprecipitation")]
public bool HasPrecipitation { get; set; }
[Column("precipitationtype")]
public string PrecipitationType { get; set; }
[Column("isdaytime")]
public bool IsDayTime { get; set; }
[ForeignKey("Temperature")]
[Column("temperatureid")]
public int TemperatureId { get; set; }
[Column("mobilelink")]
public string MobileLink { get; set; }
[Column("link")]
public string Link { get; set; }
[NotMapped]
public Temperature Temperature { get; set; }
}
[Table("temperature")]
public class Temperature
{
[Key, Column("tepmeratureid")]
public int TemperatureId { get; set; }
[ForeignKey("Imperial")]
[Column("imperialid")]
public int ImperialId { get; set; }
[ForeignKey("Metric")]
[Column("metricid")]
public int MetricId { get; set; }
[NotMapped]
public CurrentWeather CurrentWeather { get; set; }
[NotMapped]
public TemperatureUnit Imperial { get; set; }
[NotMapped]
public TemperatureUnit Metric { get; set; }
}
public class TemperatureUnit
{
public double Value { get; set; }
public Unit Unit { get; set; }
public int UnitType { get; set; }
[NotMapped]
public Temperature Temperature { get; set; }
}
public enum Unit { C,F}
I am using Mysql and Net.core EF6
When adding data only table 1 gets the data but the other two don't HELP!!!

Your json object doesn't match your database tables, so you'll have to do some mapping of those properties.
Note: the below code leaves off several properties, but you should be able to follow this and add them in as needed.
First, you need to make your json string into an object. If passed in from a controller you can use model binding; otherwise you'll have to deserialize it. Here's an appropriate view model for that:
public class CurrentWeatherViewModel
{
public DateTime LocalObservartionTime { get; set; }
public int EpochTime { get; set; }
public string WeatherText { get; set; }
//additional props here
public TemperatureViewModel Temperature { get; set; }
}
public class TemperatureViewModel
{
public MetricViewModel Metric { get; set; }
public ImperialViewModel Imperial { get; set; }
}
public class MetricViewModel
{
public decimal Value { get; set; }
public string Unit { get; set; }
public int UnitType { get; set; }
}
public class ImperialViewModel
{
public decimal Value { get; set; }
public string Unit { get; set; }
public int UnitType { get; set; }
}
You can deserialize the json string into that object like this:
var jsonString = " {\"EpochTime\": 1576173000,\"WeatherText\": \"Thunderstorm\",\"WeatherIcon\": 15,\"HasPrecipitation\": true,\"Reciprocation\": \"Rain\",\"IsDayTime\": false,\"Temperature\": {\"Metric\": {\"Value\": 13.7,\"Unit\": \"C\",\"UnitType\": 17},\"Imperial\": {\"Value\": 57,\"Unit\": \"F\",\"UnitType\": 18}}}";
CurrentWeatherViewModel currentWeatherViewModel = Newtonsoft.Json.JsonConvert.DeserializeObject<CurrentWeatherViewModel>(jsonString);
Once it's deserialized into the viewmodel object, you can create your entities and save them to the db:
CurrentWeather currentWeather = new CurrentWeather
{
WeatherText = currentWeatherViewModel.WeatherText,
Temperature = new Temperature
{
Measurements = new Measurement[] {
new Measurement {
Unit = currentWeatherViewModel.Temperature.Metric.Unit,
UnitType = currentWeatherViewModel.Temperature.Metric.UnitType,
Value = currentWeatherViewModel.Temperature.Metric.Value,
},
new Measurement {
Unit = currentWeatherViewModel.Temperature.Imperial.Unit,
UnitType = currentWeatherViewModel.Temperature.Imperial.UnitType,
Value = currentWeatherViewModel.Temperature.Imperial.Value,
}
}
}
};
db.CurrentWeathers.Add(currentWeather);
db.SaveChanges();
Here's the entity classes:
public class CurrentWeather
{
public int Id { get; set; }
public DateTime? LocalObservartionTime { get; set; }
public int EpochTime { get; set; }
public string WeatherText { get; set; }
//additional props here
public virtual Temperature Temperature { get; set; }
}
public class Temperature
{
public int Id { get; set; }
//relationship
public int CurrentWeatherId { get; set; }
//relationship
public virtual ICollection<Measurement> Measurements { get; set; }
}
public class Measurement
{
public int Id { get; set; }
public decimal Value { get; set; }
public string Unit { get; set; }
public int UnitType { get; set; }
//relationship
public int TemperatureId { get; set; }
public virtual Temperature Temperature { get; set; }
}

Related

Xamarin Json parsing

Ι am having a json like this:
{"userTweetsList":[{"tweetId":1,"tweetData":"testing uploading from uwp","createdTime":1510822592529,"commentCount":0,"likeCount":1,"flagCount":1,"mediaUrl":"suburl","tweetUser":"geo.thomas","userLiked":true,"userFlagged":true},{"tweetId":2,"tweetData":"Testing tweet","createdTime":1510821224655,"commentCount":0,"likeCount":0,"flagCount":1,"mediaUrl":"suburl","tweetUser":"sreejith.sree","userLiked":false,"userFlagged":true}],"tweetUsersMapList":[{"geo.thomas":{"username":"geo.thomas","name":"geo thomas ","profileImage":null}},{"sreejith.sree":{"username":"sreejith.sree","name":"sreejith sreenivasan","profileImage":null}}],"urlFileserverDynamic":"MyBaseUrl"}
My model class:
public class UserTweetResponse
{
public List<UserTweetsList> userTweetsList { get; set; }
}
public class UserTweetsList
{
public int tweetId { get; set; }
public string tweetData { get; set; }
public string createdTime { get; set; }
public int commentCount { get; set; }
public int likeCount { get; set; }
public int flagCount { get; set; }
public string mediaUrl { get; set; }
public string tweetUser { get; set; }
public bool userLiked { get; set; }
public bool userFlagged { get; set; }
public bool isMediaUrlNull { get { return string.IsNullOrEmpty(mediaUrl); } }
}
In my cs file, I link the listview with the userTweetsList, My listview name is ListView1.
ListView1.ItemsSource = userTweetResponse.userTweetsList;
I can access the all the data in the userTweetsList using {binding} property.
My problem is I need to access and show the name in ui based on the tweet user value. Suppose the "tweetUser":"geo.thomas" i need to access the
{"geo.thomas":{"username":"geo.thomas","name":"geo thomas ","profileImage":null}} inside the tweetUsersMapList, same way for "tweetUser":"sreejith.sree"
i need the data
{"sreejith.sree":{"username":"sreejith.sree","name":"sreejith sreenivasan","profileImage":null}}
For this I change the model like this:
public class UserTweetResponse
{
public List<UserTweetsList> userTweetsList { get; set; }
public List<TweetUsersMapList> tweetUsersMapList { get; set; }
}
public class UserTweetsList
{
public int tweetId { get; set; }
public string tweetData { get; set; }
public string createdTime { get; set; }
public int commentCount { get; set; }
public int likeCount { get; set; }
public int flagCount { get; set; }
public string mediaUrl { get; set; }
public string tweetUser { get; set; }
public bool userLiked { get; set; }
public bool userFlagged { get; set; }
public bool isMediaUrlNull { get { return string.IsNullOrEmpty(mediaUrl); } }
}
public class TweetUsersMapList
{
public string username { get; set; }
public string name { get; set; }
public string profileImage { get; set; }
}
But i don't know how to do the rest part. How can i link the listview with tweetUsersMapList? Based on the tweetUser name how can i pick the name and show that in the ui?
Is it possible to parse this type of complex json?
Anybody, please suggest a solution
Thanks in advance...
public class UserTweetsList
{
public int tweetId { get; set; }
public string tweetData { get; set; }
public object createdTime { get; set; }
public int commentCount { get; set; }
public int likeCount { get; set; }
public int flagCount { get; set; }
public string mediaUrl { get; set; }
public string tweetUser { get; set; }
public bool userLiked { get; set; }
public bool userFlagged { get; set; }
}
public class GeoThomas
{
public string username { get; set; }
public string name { get; set; }
public object profileImage { get; set; }
}
public class SreejithSree
{
public string username { get; set; }
public string name { get; set; }
public object profileImage { get; set; }
}
public class TweetUsersMapList
{
public GeoThomas __invalid_name__geo.thomas { get; set; }
public SreejithSree __invalid_name__sreejith.sree { get; set; }
}
public class RootObject
{
public List<UserTweetsList> userTweetsList { get; set; }
public List<TweetUsersMapList> tweetUsersMapList { get; set; }
public string urlFileserverDynamic { get; set; }
}
I have used Json2csharp to generate these classes...

I am a new bee with JSON and I don't know how to perform serialization and deserialization in windows phone

get links will be like this - http//192.156.120.192/Projects/cricket/index.php/api/api
public class Player
{
public int playerId { get; set; }
public string playerName { get; set; }
public string specialization { get; set; }
public string battingHand { get; set; }
public string bowlingHand { get; set; }
public string bowlingType { get; set; }
public object genericId { get; set; }
public int homeTeamId { get; set; }
public int eligibleTeams { get; set; }
public object imageUrl { get; set; }
}
public class RootObject
{
public string methodName { get; set; }
public int errorCode { get; set; }
public string errorMessage { get; set; }
public List<Player> players { get; set; }
}
I am using Json.NET and it is super easy
// create a RootObject object
//..
string serializedRoot = JsonConvert.SerializeObject(myRootObject);
RootObject deserializedRoot = JsonConvert.DeserializeObject<Player>(serializedRoot);

Mvc4 model base om JSON

I am writing an mVC4 application and i would like to create a model to generate the following JSON file:
{
"area": {
"areaid": "1",
"venueid": "41",
"fnames": "12",
"s": [{"Id":1,"V":"0,1,2,2,1,1,1,0B-001,0,0,0,"},
{"Id":2,"V":"2,1,2,2,1,1,1,0B-001,0,0,0,"},
{"Id":3,"V":"3,1,2,2,1,1,1,0B-001,0,0,0,"}]
}
}
Something like that?
public class Area
{
[Key]
public int areaid { get; set; }
public int venueid { get; set; }
public int fnames { get; set; }
[ForeignKey("Id")]
public List<Book> s { get; set; }
}
public class Book
{
[Key]
public int Id { get; set; }
public string V { get; set; }
}
I think that should work. Here's the result from using Visual Studio 2013's Paste JSON as Classes feature...
public class Rootobject
{
public Area area { get; set; }
}
public class Area
{
public string areaid { get; set; }
public string venueid { get; set; }
public string fnames { get; set; }
public List<Book> s { get; set; }
}
public class Book
{
public int Id { get; set; }
public string V { get; set; }
}

Code first generating strange column

I have an MVC 4 application that is using code first to generate tables and columns in my SQL Server DB. I am trying to figure out how I ended up with an additional TABLE that was not intended. I have looked through some questions but not found the exact same problem I am having. I will try to explain this simply.
I have added a model called Associate which keeps track of associates that my client does business with. Each Associate needs a foriegn key of AssociateTypedID and RegionID.
namespace XXX.Models
{
public class Associate
{
public int AssociateId { get; set; }
public string AssociateName { get; set; }
public int AddressNumber { get; set; }
public string AddressStreet { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zipcode { get; set; }
public string MainPhoneNumber { get; set; }
public string AssociateEmail { get; set; }
public string AssociateWebsite { get; set; }
public string ContactFirstName { get; set; }
public string ContactLastName { get; set; }
public string ContactPhoneNumber { get; set; }
public string ContactEmail { get; set; }
public int RegionId { get; set; }
public int AssociateTypeId { get; set; }
public virtual ICollection<AssociateType> AssociateTypes { get; set; }
public virtual ICollection<Region> Regions { get; set; }
}
}
AND
namespace XXX.Models
{
public class AssociateType
{
public int AssociateTypeId { get; set; }
public string AssociateTypeName { get; set; }
public virtual ICollection<Associate> Associates { get; set; }
}
}
AND
namespace XXX.Models
{
public class Region
{
public int RegionId { get; set; }
public int RegionName { get; set; }
public int RegionDescription { get; set; }
public virtual ICollection<Associate> Associates { get; set; }
}
}
AND
namespace XXX.Models
{
public class XXXDb : DbContext
{
public XXXDb(): base("name=DefaultConnection")
{
}
public DbSet<Associate> Associates { get; set; }
public DbSet<AssociateType> AssociateTypes { get; set; }
public DbSet<Region> Regions { get; set; }
}
}
So I have updated my code above and I'm getting very close to where I need to be in my database. I have the following tables generated.
Associates, AssociateTypes & Regions (each of them have the columns I would expect)
BUT I now have a new table called RegionAssociates which has the following columns:
Region_RegionId (int) & Associate_AssociateId (int)
This table was not expected or needed in my schema.
Your classes doesn't match your description of the model. You are saying
Each Associate can have a designation of AssociateType
I suppose that the same AssociateType can be assigned to more Associates, so there should be 1:N relationship between AssociateType and Associate.
But the Associate class defines the relationship the other way around - by convention public virtual ICollection<AssociateType> AssociateType { get; set; } creates 1:N relationship between Associate and AssociateType.
the correct definition of your classes would be
public class Associate
{
public int AssociateId { get; set; }
public string AssociateName { get; set; }
public int AddressNumber { get; set; }
public string AddressStreet { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zipcode { get; set; }
public string MainPhoneNumber { get; set; }
public string AssociateEmail { get; set; }
public string AssociateWebsite { get; set; }
public int RegionId { get; set; }
public int AssociateTypeId { get; set; }
public virtual AssociateType AssociateType { get; set; }
public string ContactFirstName { get; set; }
public string ContactLastName { get; set; }
public string ContactPhoneNumber { get; set; }
public string ContactEmail { get; set; }
public virtual ICollection<Region> Regions { get; set; }
}
public class AssociateType
{
public int AssociateTypeId { get; set; }
public string AssociateTypeName { get; set; }
public virtual ICollection<Associate> Associates { get; set; }
}
Can't say for sure what is missing from your configuration as you did't post it, but if you are using the fluent api something like this should fix the problem:
modelBuilder.Entity<AssociateType>()
.HasKey(t => t.AssociateTypeId);
modelBuilder.Entity<Associate>()
.HasRequired(t => t.AssociateType)
.WithRequiredPrincipal(t => t.Associate);
The above is adapted from this article http://msdn.microsoft.com/en-us/data/jj591620.aspx

How to get nested JSON Reply with WCF an Entity Framework

I have 2 models, A Order Header and Order Detail.
I want to end up with a JSON reply from the Server that looks like:
--OrderHeader 1
|
--OrderDetails 1
--OrderHeader 2
|
--Order Detail 2
Would I use entity framework create some sort of sub query wand return this via my WebGet, or would I run separate queries and integrate the format after the results have been obtained?
Here are my Viewmodels:
public class OpenOrderHeader
{
public int CustomerID { get; set; }
public int OrderID { get; set; }
public int OrderUniqueNumber { get; set; }
public int NumberOfProductsOnOrder { get; set; }
public DateTime OrderDateCreated { get; set; }
public DateTime OrderDateUpdated { get; set; }
public string OrderLocalOnline { get; set; }
public int BranchID { get; set; }
public string PaymentMethod { get; set; }
public int OrderStatus { get; set; }
public string OrderCurrency { get; set; }
public decimal OrderConversionRate { get; set; }
public decimal SubTotalInclTax { get; set; }
public decimal SubTotalExclTax { get; set; }
public decimal DiscountInclTax { get; set; }
public decimal DiscountExclTax { get; set; }
public decimal ShippingInclTax { get; set; }
public decimal ShippingExclTax { get; set; }
public decimal PaymentFeeInclTax { get; set; }
public decimal PaymentFeeExclTax { get; set; }
}
public class OpenOrderProducts
{
public int OrderID { get; set; }
public string ProductSKUName { get; set; }
public int ProductSKUID { get; set; }
public string ProductSKUStockCode { get; set; }
public DateTime ProductAddedToOrder { get; set; }
public int QtyOfProductsOnOrder { get; set; }
public decimal UnitPriceinclTax { get; set; }
public decimal UnitPriceExclTax { get; set; }
public decimal UnitDiscountInclTax { get; set; }
public decimal UnitDiscountExclTax { get; set; }
public decimal LineItemTotalIncludingTax { get; set; }
public decimal LineItemExclTax { get; set; }
public decimal LineItemShippingCost { get; set; }
}
Just create a navigation property Orderdetails on the OrderHeader entity. Then you can query
var data = db.OrderHeaders.Include(h => h.Orderdetails).ToList();
and serialize data into JSON.
I think that in the classes you show OpenOrderHeader would have a collection of OpenOrderProducts?
public virtual ICollection<OpenOrderProduct> OpenOrderProducts { get; set; }
(As you see, I would change the name of the class in OpenOrderProduct, no plural)