Should I create the "Id" property when modeling a LINQ cosmos db? - c#

Let's suppose that I want to create the following document
{
"Id": "6a23a5f3-0f77-40a9-b9f9-26e88537a962",
"CarHistory": [
{ "model":"ford", "price": 100, "kilometers": 100 "current": true },
{ "model":"ford", "price": 200, "kilometers": 200, "current": false },
]
}
In Poco I guess that the model could look something among these lines:
public class Document
{
public Guid Id { get; set; }
}
public class Car : Document
{
public string Model {get; set;}
public decimal Price {get; set;}
public int Kilometers {get; set;}
public bool Current {get; set;}
}
So later I create..
public class MasterCar : Document
{
public ICollection<Car> CarHistory { get; set; } = new List<Car>();
}
All seems to work fine while debugging:
I create the Guid programmatically somewhere in a service like:
var masterCar = new MasterCar(){ Id = Guid.NewGuid() }
but when I go to the cosmos db emulator and a SELECT * FROM , and I checkout the Id property its value is:
"id": "00000000-0000-0000-0000-000000000000",
Can someone point me what Im doing wrong? or how this should be accomplished, I read that
you should not provide an Id yourself, BUT how can I access the Id property programmatically then?
For example:
CarService.GetById(Car.Id); //Id property doesnt exist if there is no property in poco

Below is my test code, you can have a try:
Document.cs
public class Document
{
[JsonProperty("id")]
public Guid Id { get; set; }
}
Car.cs
public class Car
{
[JsonProperty("model")]
public string Model { get; set; }
[JsonProperty("price")]
public decimal Price { get; set; }
[JsonProperty("kilometers")]
public int Kilometers { get; set; }
[JsonProperty("current")]
public bool Current { get; set; }
public override string ToString()
{
return JsonConvert.SerializeObject(this);
}
}
MasterCar.cs
public class MasterCar : Document
{
public ICollection<Car> CarHistory { get; set; } = new List<Car>();
public override string ToString()
{
return JsonConvert.SerializeObject(this);
}
}
create and search:
var guid = Guid.NewGuid();
var masterCar = new MasterCar() { Id = guid };
var car = new Car() { Model = "ford", Price = 100, Kilometers = 100, Current = true };
var car2 = new Car() { Model = "ford", Price = 200, Kilometers = 200, Current = false };
var carHistory = masterCar.CarHistory;
carHistory.Add(car);
carHistory.Add(car2);
CosmosClient client = new CosmosClient(connection_string);
Container container = client.GetContainer(databaseId, containerName);
await container.CreateItemAsync<MasterCar>(masterCar);
ItemResponse<MasterCar> itemResponse = await container.ReadItemAsync<MasterCar>(guid.ToString("D"), new PartitionKey(guid.ToString("D")));
Console.WriteLine(itemResponse.Resource.ToString());
Result:

Related

To list the records from a Linq query using the model class in API controller

In API controller, I am trying to map manually author's list of article to the corresponding modelDTO. I am using the model class AuthorDTO and NewsContentDTO to list author details and his corresponding articles. Looking for someone help to map all NewContents of an author from linq result to AuthorDTO and to return AuthorDTO with the details of an author and its corresponding all news contents. How can I poppulate NewsContents in AuthorDTO from the result coming from GetHeroAuthor()
public class AuthorDTO
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public List<NewsContentDTO> NewsContents { get; set; }
}
public class NewsContentDTO
{
public int Id { get; set; }
public string Category { get; set; }
public string ContentTitle { get; set; }
public AuthorDTO Author { get; set; }
}
In API controller
var authors = _authorRepo.GetHeroAuthor();
AuthorDTO author = new AuthorDTO()
{
FirstName = authors.FirstName,
LastName = authors.LastName
NewsContents = New List<NewsContentDTO>()
{
Category = authors.NewsContents.Category,
ContentTitle = authors.NewsContents.ContentTitle
}
};
return(author);
List of Records is coming from repo
{
"id": 2,
"firstName": "My",
"lastName": "Name",
"newsContents": [
{
"id": 2,
"category": "Story",
"contentTitle": "Shopping Trip",
},
{
"id": 3,
"category": "Story",
"contentTitle": "Rainy day",
}
]
}
As you've not explicitly provided a question I presume your challenge is mapping a list of subitems.
AuthorDTO author = new AuthorDTO()
{
FirstName = authors.FirstName,
LastName = authors.LastName
// THIS WON'T WORK
NewsContents = New List<NewsContentDTO>()
{
Category = authors.NewsContents.Category,
ContentTitle = authors.NewsContents.ContentTitle
}
// TO MAP A SOURCE LIST TO TARGET LIST, TRY THIS ...
NewsContents = authors.NewsContents.Select(nc => new NewsContentDTO()
{
Category = nc.Category,
ContentTitle = nc.ContentTitle
}).ToList();
};

Mongodb C# Update element in an multiple array with multiple values

I want to update the single document in collection with the guid as filter and update value is cityType. Every guid has different citytype here i have used 3 types it may be more.
So please give a right implementation using c# code.
Models:
public class Country
{
[BsonId]
public ObjectId Id { get; set; }
public int CountryId {get; set; }
public IEnumerable<States> States { get; set; }
}
public class States
{
public Guid Guid { get; set; }
public CityType CityType { get; set; }
}
Enum CityType
{
Unknown = 0,
Rural = 1,
Urban = 2
}
Existing Collection:
{
"_id": ObjectId("6903ea4d2df0c5659334e763"),
"CountryId": 200,
"States": [
{
"Guid": "AFCC4BE7-7585-5E46-A639-52F0537895D8",
"CityType": 0,
},
{
"Guid": "208FB603-08C7-46D9-B0C0-7AF4F691A96D",
"CityType": 0,
}
}
Input:
List<States>()
{
new States()
{
Guid = "AFCC4BE7-7585-5E46-A639-52F0537895D8",
CityType = CityType.Rural
},
new States()
{
Guid = "208FB603-08C7-46D9-B0C0-7AF4F691A96D",
CityType = CityType.Urban
}
}
Expected:
{
"_id": ObjectId("6903ea4d2df0c5659334e763"),
"CountryId": 200,
"States": [
{
"Guid": "AFCC4BE7-7585-5E46-A639-52F0537895D8",
"CityType": 1,
},
{
"Guid": "208FB603-08C7-46D9-B0C0-7AF4F691A96D",
"CityType": 2,
}
}
This is the method I have tried:
public async Task<bool> UpdateType(int countryId, IEnumerable<States> states)
{
var collection = connectionFactory.GetCollection<Country>(collectionName);
var cityTypes = states.Select(x => x.CityType);
var filter = Builders<Country>.Filter.Empty;
var update = Builders<Country>.Update.Set("States.$[edit].CityType", cityTypes);
var arrayFilters = new List<ArrayFilterDefinition>();
foreach (var state in states)
{
ArrayFilterDefinition<Country> optionsFilter = new BsonDocument("state.Guid", new BsonDocument("$eq", state.Guid));
arrayFilters.Add(optionsFilter);
}
var updateOptions = new UpdateOptions { ArrayFilters = arrayFilters };
var result = await collection.UpdateOneAsync(filter, update, updateOptions);
return result;
}
hope all details I have added here. Thanks in advance.
You don't have to loop through it:
Let's say you have a Class1 like this:
class Question : AuditableEntity {
public string Text { get; set; }
public List<string> Tags { get; set; } = new List<string>();
so you just say:
await collection.UpdateOneAsync(
someFilter,
Builders<Class1>.Update
.Set(f => f.Text, request.Question.Text)
.Set(f => f.Tags, request.Question.Tags));

Adding Fulfillment to Shopify orders

This is my code in adding Fulfillment to Shopify orders but the converted json is not as expected.
Fullfillment product = new Fullfillment();
product.status = "success";
product.tracking_number = orderSent.TrackingNo;
List<LineItems> items = new List<LineItems>();
foreach (var item in orderSent.OrderLines)
{
LineItems line = new LineItems();
line.id = item.ProductName;
items.Add(line);
}
var json = JsonConvert.SerializeObject(product);
json = "{ \"fulfillment\": " + json + "}";
var json1 = JsonConvert.SerializeObject(items);
json = json + "{ \"line_items\": " + json1 + "}";
And this the converted json from this code:
{ "fulfillment": {
"id":0,
"status":"success",
"tracking_number":"xxxx12222",
}}{
"line_items": [
{
"id":"1234566645"
}
]
}
How can I turned like this:
{
"fulfillment": {
"tracking_number": null,
"line_items": [
{
"id": 466157049,
"quantity": 1
}
]
}
}
Model:
[JsonObject(MemberSerialization = MemberSerialization.OptIn)]
public class Fullfillment
{
[JsonProperty(PropertyName = "id")]
public long id { get; set; }
[JsonProperty(PropertyName = "status")]
public string status { get; set; }
[JsonProperty(PropertyName = "tracking_number")]
public string tracking_number { get; set; }
}
[JsonObject(MemberSerialization = MemberSerialization.OptIn)]
public class LineItems
{
[JsonProperty(PropertyName = "id")]
public string id { get; set; }
}
These are the models for Fulfillment and Line Items.
Thank you in advance for giving advices and help.
This works for me:
var json = JsonConvert.SerializeObject(new
{
fullfillment = new
{
product.tracking_number,
line_items = items.Select(x => new
{
x.id,
quantity = 1
})
}
});
That gives me:
{
"fullfillment" : {
"tracking_number" : "xxxx12222",
"line_items" : [{
"id" : "1234566645",
"quantity" : 1
}
]
}
}
I started with this code to build up the JSON above:
Fullfillment product = new Fullfillment();
product.status = "success";
product.tracking_number = "xxxx12222";
List<LineItems> items = new List<LineItems>();
LineItems line = new LineItems();
line.id = "1234566645";
items.Add(line);
Obviously you need to fill in your specific data.
Change your classes like below.
public class Rootobject
{
public Fulfillment fulfillment { get; set; }
}
public class Fulfillment
{
public string tracking_number { get; set; }
public Line_Items[] line_items { get; set; }
}
public class Line_Items
{
public string id { get; set; }
public int quantity { get; set; }
}
public class JsonTest
{
public void Test()
{
var root = new Rootobject();
root.fulfillment = new Fulfillment();
root.fulfillment.tracking_number = "xxxx12222";
root.fulfillment.line_items = new List<Line_Items>() { new Line_Items() { id = "1234566645", quantity = 1 } }.ToArray();
var json = JsonConvert.SerializeObject(root);
Console.WriteLine(json);
}
}
This will give you this json.
{
"fulfillment": {
"tracking_number": "xxxx12222",
"line_items": [
{
"id": "1234566645",
"quantity": 1
}
]
}
}
Try the following
public class Rootobject
{
public Fulfillment fulfillment { get; set; }
}
public class Fulfillment
{
public string tracking_number { get; set; }
public Line_Items[] line_items { get; set; }
}
public class Line_Items
{
public string id { get; set; }
public int quantity { get; set; }
}
public class JsonTest
{
public void Test()
{
var root = new Rootobject();
root.fulfillment = new Fulfillment();
root.fulfillment.tracking_number = "xxxx12222";
root.fulfillment.line_items = new List<Line_Items>() { new Line_Items() { id = "1234566645", quantity = 1 } }.ToArray();
var json = JsonConvert.SerializeObject(root);
Console.WriteLine(json);
}
}

cant figure out how to map this json into C# classes

So I have the json below that I want to Deseralize into Classes so I can work with it. But the issues is that the top two fields are a different type to all the rest
"items": {
"averageItemLevel": 718,
"averageItemLevelEquipped": 716,
"head": { ... },
"chest": { ... },
"feet": { ... },
"hands": { ... }
}
Where ... is a the Item class below, but the problem is that 2 of the fields are ints and the rest are Item, there are about 20 fields in total. So what I'd like to do is put them into a Dictionary<string, Item> but the 2 int fields are preventing me from Deseralizing it into that. I'm using JavaScriptSerializer.Deserialize<T>() to do this.
I could have each item as it's own class with the name of the item as the name of the class, but I find that to be very bad, repeating so much each time, also very hard to work with later since I cant iterate over the fields, where as I could a Dictionary. Any idea how I could overcome this?
public class Item
{
public ItemDetails itemDetails { get; set; }
public int id { get; set; }
public string name { get; set; }
public string icon { get; set; }
public int quality { get; set; }
public int itemLevel { get; set; }
public TooltipParams tooltipParams { get; set; }
public List<Stat> stats { get; set; }
public int armor { get; set; }
public string context { get; set; }
public List<int> bonusLists { get; set; }
}
Update: from the comments I came up with this solution
JObject jsonObject = JObject.Parse(json);
jsonObject["averageItemLevel"] = int.Parse(jsonObject["items"]["averageItemLevel"].ToString());
jsonObject["averageItemLevelEquipped"] = int.Parse(jsonObject["items"]["averageItemLevelEquipped"].ToString());
jsonObject["items"]["averageItemLevel"].Parent.Remove();
jsonObject["items"]["averageItemLevelEquipped"].Parent.Remove();
var finalJson = jsonObject.ToString(Newtonsoft.Json.Formatting.None);
var character = _serializer.Deserialize<Character>(finalJson);
character.progression.raids.RemoveAll(x => x.name != "My House");
return character
If I add these two classes to match your JSON I can serialize and deserialize the objects:
public class root
{
public Items items { get; set; }
}
public class Items
{
public int averageItemLevel { get; set; }
public int averageItemLevelEquipped { get; set; }
public Item head {get;set;}
public Item chest {get;set;}
public Item feet {get;set;}
public Item hands {get;set;}
}
Test rig with the WCF Serializer:
var obj = new root();
obj.items = new Items
{
averageItemLevel = 42,
feet = new Item { armor = 4242 },
chest = new Item { name = "super chest" }
};
var ser = new DataContractJsonSerializer(typeof(root));
using (var ms = new MemoryStream())
{
ser.WriteObject(ms, obj);
Console.WriteLine(Encoding.UTF8.GetString(ms.ToArray()));
Console.WriteLine("and deserialize");
ms.Position = 0;
var deserializeObject = (root) ser.ReadObject(ms);
Console.WriteLine(deserializeObject.items.feet.armor);
}
And with the JavaScriptSerializer:
var jsser = new JavaScriptSerializer();
var json = jsser.Serialize(obj);
Console.WriteLine(json);
Console.WriteLine("and deserialize");
var djson = jsser.Deserialize<root>(json);
Console.WriteLine(djson.items.feet.armor);
Both serializers give the same result for your given JSON.

Map entity to JSON using JavaScriptSerializer

My entities are like this:
class Address
{
public string Number { get; set; }
public string Street { get; set; }
public string City { get; set; }
public string Country { get; set; }
}
class Person
{
public string Name { get; set; }
public int Age { get; set; }
public Address PostalAddress { get; set; }
}
Person newPerson =
new Person()
{
Name = "Kushan",
Age = 25,
PostalAddress =
new Address()
{
Number = "No 25",
Street = "Main Street",
City = "Matale",
Country = "Sri Lanka"
}
};
Now I wanna map this newPerson object into JSON object like this,
{
"PER_NAME" : "Kushan",
"PER_AGE" : "25",
"PER_ADDRESS" : {
"ADD_NUMBER" : "No 25",
"ADD_STREET" : "Main Street",
"ADD_CITY" : "Matale",
"ADD_COUNTRY" : "Sri Lanka"
}
}
Note: Above is just an example.
What I need is, I need to customize the Key at the serializing time. by default it is taking property name as the key. I can't change property names. How to do this?
Also, is it possible to change to order of appearing key-value pairs in JSON obj.?
You need to add DataContract attributes to your classes and DataMember to the properties. Set Name property of DataMemeber attribute to your custom property name and Order property to define the order.
[DataContract]
public class Person
{
[DataMember(Name = "PER_NAME", Order = 1)]
public string Name { get; set; }
[DataMember(Name = "PER_AGE", Order = 2)]
public int Age { get; set; }
[DataMember(Name = "PER_ADDRESS", Order = 3)]
public Address PostalAddress { get; set; }
}
Then you can do this:
var newPerson = new Person()
{
Name = "Kushan",
Age = 25,
PostalAddress = new Address()
{
Number = "No 25",
Street = "Main Street",
City = "Matale",
Country = "Sri Lanka"
}
};
MemoryStream stream = new MemoryStream();
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Person));
ser.WriteObject(stream, newPerson);
To check the result:
var result = Encoding.ASCII.GetString(stream.ToArray());
{"PER_NAME":"Kushan","PER_AGE":25,"PER_ADDRESS":{"ADD_NUMBER":"No 25","ADD_STREET":"Main Street","ADD_CITY":"Matale","ADD_COUNTRY":"Sri Lanka"}}
You can serialize an anonymous type with JavaScriptSerializer, so you might try projecting your object into the shape you want to serialize:
person.Select(s => new { PER_NAME = s.Name, PER_AGE = s.Age });

Categories

Resources