Cannot implicitly convert type 'System.Guid?' to 'DataContracts.Market' - asp.net

I am getting the following error
Cannot implicitly convert type 'System.Guid?' to 'DataContracts.Market'
private CellSite MapEntityToCellSitePOCO(t_CellSite _cellsite)
{
CellSite cellsite= new CellSite();
cellsite.SiteId = _cellsite.SiteID;
cellsite.Market.MarketID = _cellsite.MarketId;
cellsite.Region.RegionId = _cellsite.RegionId;
return cellsite;
}
the following is my datacontracts file
public class CellSite
{
public Guid CellSiteID { get; set; }
public string SiteId { get; set; }
public Region Region { get; set; }
public Market Market { get; set; }
public Guid? ConstructionManager { get; set;}
}
This is market.cs
public class Market
{
public Guid? MarketID { get; set; }
public string OperatorMarketName { get; set; }
public string MarketName { get; set; }
public decimal AllOtherAmount { get; set; }
public decimal RawLandAmount { get; set; }
public decimal RenewalFee { get; set; }
public bool IsActive { get; set; }
}
there is a column MarketId in cellsite table which i want to bring on.how can i do that? I am new to entity frame work.
thanks in advance

You have to initialize your Market and Region properties first:
CellSite cellsite= new CellSite();
cellsite.SiteId = _cellsite.SiteID;
cellsite.Market = new Market();
cellsite.Market.MarketID = _cellsite.MarketId;
cellsite.Region = new Region();
cellsite.Region.RegionId = _cellsite.RegionId;

Related

List of items relate to two tables one contain foreign key other the primary key and check if item contain primary key is not in the database insert

I have task to get list of items which contain properties related to two tables(Item, PurchaseItemOrder), This list contain the Code property related to Item class this property is not the primary key for business reasons. So I have to search in the database by this Code and if this Item does not exist in the database insert it, And finally return the Id of the Item which is the primary key and get this key as foreign key in another table PurchaseItemOrder, I did some code, and I see this question Check if List of Items exist in database and if not Add it to database, but seems not exactly what I want can I do better?
Here May Code look like:
public class Item :Entity<int> , IFullAudited<User>
{
public string Name_en { get; set; }
public string Name_ar { get; set; }
public string Code { get; set; }
public string Description_en { get; set; }
public string Description_ar { get; set; }
public User CreatorUser { get; set; }
public User LastModifierUser { get; set; }
public long? CreatorUserId { get; set; }
public DateTime CreationTime { get; set; }
public long? LastModifierUserId { get; set; }
public DateTime? LastModificationTime { get; set; }
public User DeleterUser { get; set; }
public long? DeleterUserId { get; set; }
public DateTime? DeletionTime { get; set; }
public bool IsDeleted { get; set; }
}
public class PurchaseOrderItem : Entity<int>, IFullAudited<User>
{
public int POId { get; set; }
public int Qty { get; set; }
public int ItemId { get; set; }
public virtual Item Item { get; set; }
public User CreatorUser { get; set; }
public User LastModifierUser { get; set; }
public long? CreatorUserId { get; set; }
public DateTime CreationTime { get; set; }
public long? LastModifierUserId { get; set; }
public DateTime? LastModificationTime { get; set; }
public User DeleterUser { get; set; }
public long? DeleterUserId { get; set; }
public DateTime? DeletionTime { get; set; }
public bool IsDeleted { get; set; }
public PurchaseOrder PurchaseOrder { get; set; }
}
public class PurchaseOrderItemDto : EntityDto<int>
{
public string PONumber { get; set; }
public List<ItemDto> Items { get; set; }
}
public class ItemDto :EntityDto<int>
{
public string Name_en { get; set; }
public string Name_ar { get; set; }
public string Code { get; set; }
public string Description_en { get; set; }
public string Description_ar { get; set; }
public int Qty { get; set; }
}
private int CheckPO(PurchaseOrderItemDto dto)
{
var poExist = _purchaseOrderRepository.FirstOrDefault(po => po.PONumber == dto.PONumber);
int id;
if (poExist == null)
{
id = _purchaseOrderRepository.InsertAndGetId(new PurchaseOrder
{
PONumber = dto.PONumber,
StatusId = 1
});
}
else
{
id = poExist.Id;
}
return id;
}
private int CheckItem(ItemDto itemDto)
{
var itemExist = _itemRepository.FirstOrDefault(it => it.Code == itemDto.Code);
int id;
if (itemExist == null)
{
id = _itemRepository.InsertAndGetId(new Item
{
Name_en = itemDto.Name_en,
Name_ar = itemDto.Name_en,
Code = itemDto.Code,
Description_en = itemDto.Description_en,
Description_ar = itemDto.Description_ar
});
}
else
{
id = itemExist.Id;
}
return id;
}
public void UploadPurchaseOrderItems(PurchaseOrderItemDto dto)
{
var poId = CheckPO(dto);
foreach (var poItem in dto.Items)
{
int itemId = CheckItem(poItem);
_repository.Insert(new PurchaseOrderItem
{
POId = poId,
Qty = poItem.Qty,
ItemId = itemId
});
}
}

Deserialize json without root object and 1 array ASP.NET MVC

I'm building a web application that's using a third parties API and I receive the json below
{
"CompanyID": 14585,
"CompanyName": "The Morgan Group Daytona, LLC",
"BillingAddressLine": "100 S Beach St #200",
"BillingAddressCity": "Daytona Beach",
"BillingAddressState": "Fl",
"BillingAddressPostCode": "32114",
"BillingCountryCode": "US",
"BillingAddress": "100 S Beach St #200\r\nDaytona Beach Fl 32114\r\nUNITED STATES",
"Phone": null,
"Fax": null,
"website": null,
"TaxNumber": null,
"Comments": null,
"CurrencyCode": "USD",
"DefaultTradingTermIDFK": 15,
"DateCreated": "2020-09-04T18:25:02",
"DateUpdated": "2020-09-04T18:25:02",
"Contacts": [
{
"ContactID": 13781,
"CompanyIDFK": 14585,
"CompanyName": null,
"Firstname": "Test",
"Lastname": "User",
"Email": "test#test.com",
"Phone": null,
"Mobile": "4075551234",
"PositionTitle": "Test Title",
"TimeZone": "Eastern Standard Time",
"DateCreated": "2020-09-07T02:21:10",
"DateUpdated": "2020-09-07T02:21:10"
}
]
}
All of the other json responses for the other API calls also do not have root objects. The goal is to use razor to display this information on the view. Whats the most efficient way to do so?
So far I've created this class file
public class Contact {
public int ContactID { get; set; }
public int CompanyIDFK { get; set; }
public object CompanyName { get; set; }
public string Firstname { get; set; }
public string Lastname { get; set; }
public string Email { get; set; }
public object Phone { get; set; }
public string Mobile { get; set; }
public string PositionTitle { get; set; }
public string TimeZone { get; set; }
public DateTime DateCreated { get; set; }
public DateTime DateUpdated { get; set; }
}
public class Root {
public int CompanyID { get; set; }
public string CompanyName { get; set; }
public string BillingAddressLine { get; set; }
public string BillingAddressCity { get; set; }
public string BillingAddressState { get; set; }
public string BillingAddressPostCode { get; set; }
public string BillingCountryCode { get; set; }
public string BillingAddress { get; set; }
public object Phone { get; set; }
public object Fax { get; set; }
public object website { get; set; }
public object TaxNumber { get; set; }
public object Comments { get; set; }
public string CurrencyCode { get; set; }
public int DefaultTradingTermIDFK { get; set; }
public DateTime DateCreated { get; set; }
public DateTime DateUpdated { get; set; }
public List<Contact> Contacts { get; set; }
}
but now i'm stuck on trying to figure out how to deserialize something like this? Whats the easiest way to do this. I can't seem to find any other post that matches this same set of circumstances.
When you get a blob of JSON, you can speed things up by going to https://json2csharp.com/ and have it convert it in to classes. For example, that blob returns this:
public class Contact {
public int ContactID { get; set; }
public int CompanyIDFK { get; set; }
public object CompanyName { get; set; }
public string Firstname { get; set; }
public string Lastname { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
public string Mobile { get; set; }
public string PositionTitle { get; set; }
public string TimeZone { get; set; }
public DateTime DateCreated { get; set; }
public DateTime DateUpdated { get; set; }
}
public class Root {
public int CompanyID { get; set; }
public string CompanyName { get; set; }
public string BillingAddressLine { get; set; }
public string BillingAddressCity { get; set; }
public string BillingAddressState { get; set; }
public string BillingAddressPostCode { get; set; }
public string BillingCountryCode { get; set; }
public string BillingAddress { get; set; }
public string Phone { get; set; }
public string Fax { get; set; }
public string website { get; set; }
public string TaxNumber { get; set; }
public string Comments { get; set; }
public string CurrencyCode { get; set; }
public int DefaultTradingTermIDFK { get; set; }
public DateTime DateCreated { get; set; }
public DateTime DateUpdated { get; set; }
public List<Contact> Contacts { get; set; }
}
The classes it returns will sometimes have some small issues, for example, since your blob had a lot of null properties, it just converted them to object. I changed them to string.
Then you simply use Newtonsoft.Json to convert it:
using(var s = File.OpenRead(#"c:\users\andy\desktop\test.json"))
using(var sr = new StreamReader(s))
using(var jtr = new JsonTextReader(sr))
{
var obj = new JsonSerializer().Deserialize<Root>(jtr);
}
And you are finished:
ETA
You posted your code on getting this data and noticed you are using WebRequest. Just a heads up that WebRequest is legacy and you should be using HttpClient. This is how you download/deserialize with HttpClient:
private static readonly HttpClient _httpClient = new HttpClient();
private static async Task<Root> GetStuffFromThereAsync(string token)
{
using(var req = new HttpRequestMessage(HttpMethod.Get,
new Uri("https://www.example.com")))
{
req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
using (var resp = await _httpClient.SendAsync(req))
{
resp.EnsureSuccessStatusCode();
using (var s = await resp.Content.ReadAsStreamAsync())
using (var sr = new StreamReader(s))
using (var jtr = new JsonTextReader(sr))
{
return new JsonSerializer().Deserialize<Root>(jtr);
}
}
}
}
If it is still returning null, then there is a chance your models don't match.
You need to use the below the line with class I have mentioned :
Root myDeserializedClass = JsonConvert.DeserializeObject<Root>("This is the your JSON string");
Class
public class Contact {
public int ContactID { get; set; }
public int CompanyIDFK { get; set; }
public object CompanyName { get; set; }
public string Firstname { get; set; }
public string Lastname { get; set; }
public string Email { get; set; }
public object Phone { get; set; }
public string Mobile { get; set; }
public string PositionTitle { get; set; }
public string TimeZone { get; set; }
public DateTime DateCreated { get; set; }
public DateTime DateUpdated { get; set; }
}
public class Root {
public int CompanyID { get; set; }
public string CompanyName { get; set; }
public string BillingAddressLine { get; set; }
public string BillingAddressCity { get; set; }
public string BillingAddressState { get; set; }
public string BillingAddressPostCode { get; set; }
public string BillingCountryCode { get; set; }
public string BillingAddress { get; set; }
public object Phone { get; set; }
public object Fax { get; set; }
public object website { get; set; }
public object TaxNumber { get; set; }
public object Comments { get; set; }
public string CurrencyCode { get; set; }
public int DefaultTradingTermIDFK { get; set; }
public DateTime DateCreated { get; set; }
public DateTime DateUpdated { get; set; }
public List<Contact> Contacts { get; set; }
}

Data Model structure for farm related project

I am currently trying to figure out a data model and struggling as its getting quite complex. What I've got so far is explained below. I'm going to implement this in an ASP.NET CORE MVC app to help with managing the harvest remotely.
The data model is as follows: Farms can have multiple fields, each field can have multiple types of crop. Each farm can also have multiple harvests with different crops to which I need to be able to store information about the total crop yield, for that harvest, that's specific to that farm. Any help would be greatly appreciated!
Thanks!
Attempted data model -
https://imgur.com/a/tgGIRNq
Edit - Sorry didn't specify how I would like an answer. The Entities as below:
I currently have -
public class Farm : IEntityBase<int>
{
public int Id { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public ICollection<Field> Fields { get; set; }
public DateTime CreationTime { get; set; }
public ICollection<Harvest> Harvests { get; set; }
public Farm()
{
CreationTime = DateTime.Now;
}
}
public class Crop : IEntityBase<int>
{
public int Id { get; set; }
public DateTime CreationTime { get; set; }
public string CropName { get; set; }
public Crop()
{
CreationTime = DateTime.Now;
}
}
public class Field : IEntityBase<int>
{
public int Id { get; set; }
public string Name { get; set; }
public int FieldId { get; set; }
public DateTime CreationTime { get; set; }
public int FieldSize { get; set; }
public ICollection<Crop> Crops { get; set; }
public Field()
{
CreationTime = DateTime.Now;
}
}
public class Harvest:IEntityBase<int>
{
public int Id { get; set; }
public DateTime CreationTime { get; set; }
public int FarmId { get; set; }
public DateTime HarvestYear { get; set; }
public Crop Crop { get; set; }
public Harvest()
{
CreationTime = DateTime.Now;
HarvestYear = DateTime.Now;
}
}

Newtonsoft serialization

I need some help with custom serialization using Newtonsoft Json (Json.Net). I have classes like below:
public class Person
{
[JsonProperty(PropertyName = "PersonName")]
public string Name { get; set; }
[JsonIgnore]
public int Age { get; set; }
public Address PersonAddress { get; set; }
}
public class Address
{
[JsonProperty(PropertyName = "Address1")]
public string Address1 { get; set; }
[JsonIgnore]
public string Address2 { get; set; }
[JsonProperty(PropertyName = "City")]
public string City { get; set; }
[JsonProperty(PropertyName = "State")]
public string State { get; set; }
[JsonIgnore]
public string Country { get; set; }
}
When I serialize the above class it should return output like below:
{
"PersonName":"Name",
"Address1":"Address1",
"City":"City",
"State":"state"
}
How can I do it using Newtonsoft?
You can create a third class as follows:
public class Rootobject
{
public string PersonName { get; set; }
public string Address1 { get; set; }
public string City { get; set; }
public string State { get; set; }
}
Then, an object out of it like this:
var rootObject = new Rootobject()
{
PersonName = person.Name,
Address1 = address.Address1,
City = address.City,
State = address.State
};
And finally serialize it using JsonCovert:
var result = JsonConvert.SerializeObject(rootObject);

ServiceStack, OrmLite Issue Saving Related Entities

I've searched for a while looking for a solution to this problem and haven't found anything.
I'm trying to POST a Client DTO and it's related Contacts DTOs to my ServiceStack web service but I'm getting an error. I've followed along with the OrmLite tests located here.
My DTOs:
public partial class Client {
[AutoIncrement]
public int ID { get; set; }
public string Street { get; set; }
public string City { get; set; }
public string State { get; set; }
public string ZipCode { get; set; }
public decimal? Latitude { get; set; }
public decimal? Longitude { get; set; }
public string HomePhoneAreaCode { get; set; }
public string HomePhoneExchange { get; set; }
public string HomePhoneNumber { get; set; }
public string HomeFaxAreaCode { get; set; }
public string HomeFaxExchange { get; set; }
public string HomeFaxNumber { get; set; }
public string KeyNumber { get; set; }
public string AlarmCode { get; set; }
public string GarageDoorCode { get; set; }
public string MyAPCUsername { get; set; }
public string MyAPCPassword { get; set; }
public bool IsActive { get; set; }
public string Notes { get; set; }
[Reference]
public List<Contact> Contacts { get; set; }
}
public partial class Contact {
[AutoIncrement]
public int ID { get; set; }
public int ClientID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string WorkPhoneAreaCode { get; set; }
public string WorkPhoneExchange { get; set; }
public string WorkPhoneNumber { get; set; }
public string MobilePhoneAreaCode { get; set; }
public string MobilePhoneExchange { get; set; }
public string MobilePhoneNumber { get; set; }
public bool CanSMS { get; set; }
public string PersonalEmail { get; set; }
public string WorkEmail { get; set; }
public string AlternateEmail { get; set; }
public int Ordinal { get; set; }
[Reference]
public Client Client { get; set; }
}
In my Service:
public int Post(Client client) {
Db.Save(client, references: true);
return client.ID;
}
And my test code:
var newClient = new Client {
Street = "1234 Any Avenue",
City = "Gorham",
State = "ME",
ZipCode = "22222",
HomePhoneAreaCode = "123",
HomePhoneExchange = "456",
HomePhoneNumber = "7890",
HomeFaxAreaCode = "098",
HomeFaxExchange = "765",
HomeFaxNumber = "4321",
KeyNumber = "99",
AlarmCode = "1234",
GarageDoorCode = "abcd",
IsActive = true,
Notes = "These are the notes for the new client.",
Contacts = new List<Contact>() {
new Contact { FirstName = "John", LastName = "Doe", PersonalEmail = "john.doe#gmail.com", CanSMS = true, Ordinal = 1 },
new Contact { FirstName = "Jane", LastName = "Smith", PersonalEmail = "jane.smith#gmail.com", CanSMS = false, Ordinal = 2 }
},
};
// POST entity
int newClientID = serviceClient.Post<int>(newClient);
The last line produces the error -
WebServiceException, message "Cant find 'ClientId' Property on Type 'Contact'"
I've tried different combinations of the Reference, References, and ForeignKey attributes to no avail.
Any help would be appreciated.
Thanks,
Jay

Resources