I am trying to fetch data from inside mongodb.
I am getting the following exception:
System.TypeInitializationException: 'The type initializer for 'MongoDB.Bson.Serialization.BsonClassMap' threw an exception.'
ArgumentNullException: Value cannot be null. Arg_ParamName_Name
public IQueryable<IssueDto> FetchCollection(string databaseName, string collectionName)
{
var dbClient =
new MongoClient("mongo connection string here");
var database = dbClient.GetDatabase(databaseName);
var collection = database.GetCollection<IssueDto>(collectionName);
return collection.AsQueryable();
}
Json inside mongo:
{
"_id":{"$oid":"63920bcf14ab25ab93444804"},
"name":"This is a task",
"completed": true,
"issueId":1234
}
The model class is as follows:
public class IssueDto
{
[BsonElement("_id")]
public ObjectId Id { get; set; }
[BsonElement("issueId")]
public int IssueId { get; set; }
[BsonElement("name")]
public string Name { get; set; }
[BsonElement("completed")]
public bool Completed { get; set; }
}
Can anyone spot what is going wrong?
Other info: .NET6, MongoDB.Driver 2.8.0
Related
I have this JSON response that is produced from a POST request that I have sent.
{
"correlationID": "00000000-0000-0000-0000-000000000000",
"scenarioID": 2,
"scenarioIsAcceptedInPrinciple": false,
"valid": false,
"errors": [
{
"errorID": 90,
"errorText": "For the 1st Employment of the 1st Applicant Please provide a valid Landline"
},
{
"errorID": 22,
"errorText": "The provided value 'string' is not a valid value for the property 'applicants[0][email]'"
}
]
}
I would like to deserialize it so I can get the errorID and errorText and do testing assertions to see if the correct error ID and text came back.
I have got it to work with:
public partial class postRequest
{
public bool Valid { get; set; }
public object Errors { get; set; }
}
and it returns all of the error, like this:
Standard Output:
[
{
"errorID": 90,
"errorText": "For the 1st Employment of the 1st Applicant Please provide a valid Landline"
},
{
"errorID": 22,
"errorText": "The provided value 'string' is not a valid value for the property 'applicants[0][email]'"
}
]
How would I return just the error ID and error text?
Thanks
You should create another class for the error.
public class Error
{
public string ErrorID { get; set; }
public string ErrorText { get; set; }
}
And then use that in the other class:
public Error[] Errors { get; set; }
Finally you access the errors like:
response.Errors[0].ErrorID
You have to deserialize it like this object :
public class JsonResponse
{
public bool valid { get; set; }
public List<Error> errors { get; set; }
}
public class Error
{
public int errorID { get; set; }
public string errorText { get; set; }
}
For deserialization:
var data =System.Text.Json.JsonSerializer.Deserialize<JsonResponse>("your json source");
you have a list of errors, not just a one
List<Error> errors = JObject.Parse(json)["errors"].Select(x => x.ToObject<Error>()).ToList();
public class Error
{
public int ErrorID { get; set; }
public string ErrorText { get; set; }
}
you can see them
foreach (var error in errors)
{
Console.WriteLine($"Error Id : {error.ErrorID}, Error Text {error.ErrorText}");
}
// or
var errId=errors[0].ErrorID;
I am facing problem in asp.net for fetching data from MongoDB and got an error. Please help me to resolve this error.
Error :
Cannot deserialize a 'ObjectId' from BsonType 'Null'.Description: An
unhandled exception occurred during the execution of the current web
request. Please review the stack trace for more information about the
error and where it originated in the code.
Exception Details:
System.FormatException: Cannot deserialize a 'ObjectId' from BsonType
'Null'.
public partial class Loginpage : System.Web.UI.Page
{
protected void Button1_Click(object sender, EventArgs e)
{
String connectionstring = "mongodb://localhost";
var client = new MongoClient(connectionstring);
var database = client.GetDatabase("SIH");
bool isMongoLive = database.RunCommandAsync((Command<BsonDocument>)"{ping:1}").Wait(1000);
if (isMongoLive)
{
var collection = database.GetCollection<userinfo>("userinfo");
// var id = new ObjectId("5a6b35217e60af482bedef33");
var idd = TextBox1.Text;
//var userinfo = collection.Find(b => b._id == id).ToListAsync().Result;
var userinfo = collection.Find(b => b.name == idd).ToListAsync().Result; // Due to this i got an error
foreach (var user in userinfo)
{
Response.Write(user.phoneno);
}
}
else
{
Response.Write("Hello dude your server is not connected !! ");
}
}
}
public class userinfo
{
//public ObjectId _id { get; set; }
public string name { get; set; }
public string emailid { get; set; }
public string password { get; set; }
public string phoneno { get; set; }
public string activate { get; set; }
public string block { get; set; }
}
Seems like in SIH collection one of your documents has a null ObjectId
You can make your code work by making _id nullable public ObjectId? _id { get; set; }
I am new to Mongodb, so please execute if my question is elementary. I am using the Mongodb C# driver in my ASP.net MVC project. However, while executing the MongoDb C# update operation, I am hitting this error
Maximum serialization depth exceeded (does the object being serialized have a circular reference?).
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: MongoDB.Bson.BsonSerializationException: Maximum serialization depth exceeded (does the object being serialized have a circular reference?).
Here is the object model class. Is the error due to the below line, which is there in my model class?
public List OutGoingFriendRequestList { get; set; }
public class UserProfileViewModel
{
public ObjectId Id { get; set; }
public string UserId { get; set; }
public string Email { get; set; }
public string DisplayName { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string UserDescription { get; set; }
public string UserName { get; set; }
public List<UserProfileViewModel> OutGoingFriendRequestList { get; set; }
}
}
And here is the Controller Action Method in which I try to do the update
public async Task<ActionResult> AddFriend(UserProfileViewModel model)
{
//Get the database connection instance and then get the collection
var _database = SocialNetworkHelper.ReturnMongoDbInstance();
IMongoCollection<UserProfileViewModel> collection =
_database.GetCollection<UserProfileViewModel>("Facebook_Lite");
//In the next 2 sentences, I am filtering using the userId field
string userId = User.Identity.GetUserId();
var filter = Builders<UserProfileViewModel>.Filter.Eq("UserId", User.Identity.GetUserId());
var result = collection.Find(filter).ToListAsync();
result.Wait();
UserProfileViewModel userProfileViewModelInstance = result.Result.ElementAt(0);
List<UserProfileViewModel> OutgoingFriendRequestList = userProfileViewModelInstance.OutGoingFriendRequestList;
OutgoingFriendRequestList.Add(friendUserModelInstance);
userProfileViewModelInstance.OutGoingFriendRequestList = OutgoingFriendRequestList;
var update = Builders<UserProfileViewModel>.Update.Set("OutGoingFriendRequestList", userProfileViewModelInstance.OutGoingFriendRequestList);
//I am hitting the exception on the below line
**var updateResult = await collection.UpdateOneAsync(filter, update);**
return RedirectToAction("Index", "Home", new { userid = friendUserId });
}
The way you represent a tree like model like yours is by holding references to children/leaves, not the objects themselves. Instead of:
public List<UserProfileViewModel> OutGoingFriendRequestList { get; set; }
you should store ids of these database redords.
public List<ObjectId> OutGoingFriendRequestList { get; set; }
I have this error during save on update data in my mongo db.
this is erorr:
Save can only be used with documents that have an Id.
this is my model:
public ModelKorisici () { }
[BsonId(IdGenerator = typeof(CombGuidGenerator))] // posajvljivaa se greška kod BSON tipa podataka kod ID-a,preuzoteo s dokumentacije drivera 1.5
public Guid Id { get; set; }
[BsonElement("ime")]
public string ime { get; set; }
[BsonElement("prezime")]
public string prezime { get; set; }
[BsonElement("lozinka")]
public string lozinka { get; set; }
[BsonElement("email")]
public string email { get; set; }
[BsonElement("kor_ime")]
public string kor_ime { get; set; }
[BsonElement("uloga")]
public string uloga { get; set; }
}
My code for update is here:
public void urediKorisnika(ModelKorisici korisnik)
{
MongoCollection<ModelKorisici> kljenti = GetTasksCollection();
kljenti.Save(kljenti);
}
Can anyone help?
I'm not sure what are you trying to do but your error is in following code block
public void urediKorisnika(ModelKorisici korisnik)
{
MongoCollection<ModelKorisici> kljenti = GetTasksCollection();
kljenti.Save(kljenti);
}
Here are you trying to store collection to itself. I believe GetTasksCollection() return collection from MongoDB and then you are trying to store it into itself again. see kljenti.Save(kljenti);
You need to create instance of ModelKorisici and save it into kljenti
Your code should look something like:
public void urediKorisnika(ModelKorisici korisnik)
{
MongoCollection<ModelKorisici> kljenti = GetTasksCollection();
var model = new ModelKorisici();
model.ime = ...
...
kljenti.Save(model);
}
Here is the sample data from a collection. Basically the only thing that I am trying to do is read all of the data like this in as a "Student" but it is throwing an error for some reason. It works fine when I read them all in as Bson documents but that is not what I want to do. Here is the error:
An unhandled exception of type 'System.AggregateException' occurred in mscorlib.dll
Additional information: One or more errors occurred.
what am I doing wrong?
{
"_id" : 137,
"name" : "Tamika Schildgen",
"scores" : [
{
"type" : "exam",
"score" : 4.433956226109692
},
{
"type" : "quiz",
"score" : 65.50313785402548
},
{
"type" : "homework",
"score" : 89.5950384993947
}
]
}
static async Task MainAsync(string[] args)
{
var client = new MongoClient();
var db = client.GetDatabase("school");
var col = db.GetCollection<Student>("students");
var list = await col.Find(new BsonDocument())
.ToListAsync();
foreach(var doc in list)
{
Console.WriteLine(doc);
}
}
}
class Student
{
public ObjectId Id { get; set; }
public string name { get; set; }
public Scores[] scores { get; set; }
}
class Scores
{
public string type { get; set; }
public double score { get; set; }
}
The error lies in Id field type:
If you turn on the option of breaking execution when a CLR exception is thrown (Menu Debug|Exceptions), you will see a message similar to: "An error occurred while deserializing the Id property of class ConsoleApplication2.Student: Cannot deserialize a 'ObjectId' from BsonType 'Double'."
If you change the class Student to:
public class Student
{
public int Id { get; set; }
public string name { get; set; }
public Scores[] scores { get; set; }
}
the exception will not be thrown anymore.
(Additionally, to get readable results, you should probably override ToString() method for Student class).