Error during update data on mongo db - c#

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);
}

Related

Merge two identical object model class after JsonConvert.DeserializeObject

C# and Newtonsoft.JSON
I've an object model class like this
class RolePerson
{
public NodeRolePerson[] Items { get; set; }
}
class NodeRolePerson
{
public bool active { get; set; }
public string dateUva { get; set; }
public bool delegated { get; set; }
public NodeentityOrg entityOrg { get; set; }
.....
public string userUva { get; set; }
}
.........
Now i get data with
RolePerson myP1 = JsonConvert.DeserializeObject<RolePerson>(data1,settings);
RolePerson myP2 = JsonConvert.DeserializeObject<RolePerson>(data2,settings);
How can i have only one object with both myP1 and myP2 ?
I've tried with
List<RolePerson> trace;
trace.Add(myP1);
trace.Add(myP2);
but receive a compilation error 'local variable not assigned'.
Thanks so much.
You never actually created a new list:
List<RolePerson> trace = new List<RolePerson>();
trace.Add(myP1);
trace.Add(myP2);
try this
var items = new List<NodeRolePerson>(myP1.Items);
items.AddRange(myP2.Items);
RolePerson trace = new RolePerson { Items = items.ToArray() };

How to Json Element is present or not using C# (With Newtonsoft NugetPackages)

I have Json file, where i am trying the parse the data of the json file for database update with some data contions, Currently i want to check an particular element exists or not.In my current Json data, Under the Operation Node the accessRef can exist in the file or may not exist completely.So how would check the condtion. Kindly suggest me.
Below is the Json file
{
"PLMXML":{
"language":"en-us",
"time":"16:50:15",
"schemaVersion":"6",
"author":"Development(-2069033203)",
"date":"2020-05-22",
"Header":{
"id":"id1",
"traverseRootRefs":"#id6",
"transferContext":"CLM"
},
"Operation":{
"id":"id21",
"name":"PD_Op2",
"subType":"BS4_BaOP",
"accessRefs":"#id18",
"catalogueId":"70700000209604",
"ApplicationRef":{
"application":"Teamcenter",
"label":"yDX58d4FIpN8QD",
"version":"yDX58d4FIpN8QD"
}
}
}
}
Below the Code which i am trying perform
public void Readjsonfile(string jsondata)
{ var message = JsonConvert.DeserializeObject<plmxmldatamodel>(jsondata);
Console.WriteLine("RootRef: " + message.PLMXML.Header.traverseRootRefs);
Console.WriteLine("OccurenceId: "+message.PLMXML.ProductView.Operation.id);
// I want to check whtether is accessrefs is present or not inside the Operation element
}
//fuction1
public class Header
{ public string traverseRootRefs { get; set; }
}
//fuction2
public class Operation
{ public string id { get; set; }
public string name { get; set; }
public string subType { get; set; }
public string accessRefs { get; set; }
public string catalogueId { get; set; }
}
//fuction3
public class PLMXML
{
public string language { get; set; }
public Header Header { get; set; }
public Operation Operation { get; set; }
}
//fuction4
public class plmxmldatamodel
{
public PLMXML PLMXML { get; set; }
}
If empty/null value for accessRefs is a valid situation (i.e. ... "'accessRefs':, ...") then you can use JSON Path to check if it exists:
var jObj = JObject.Parse(jsondata);
if(jObj.SelectToken("$.PLMXML.Operation.accessRefs") != null)
{
// do what you want to do if accessRefs exists
}
Otherwise just check for message.PLMXML.ProductView.Operation.accessRefs not being null:
if(message.PLMXML.ProductView.Operation.accessRefs != null)
{
// do what you want to do if accessRefs exists
}

502 error while converting entity framework data to json. Possible recursion. How to prevent it?

[HttpGet("/api/notes/suggested")]
public JsonResult GetSuggestedNotes(string searchText)
{
//TODO: Podpowiedzi przy wpisywaniu tytułu
JsonResult result = null;
try {
List<Note> n = db.Notes.Include(x => x.NoteTags).ToList();
result = Json(n);
}
catch(Exception e)
{
Console.WriteLine(e);
}
return result;
}
public class Note
{
public Note()
{
CreationDate = DateTime.Now;
NoteTags = new HashSet<NoteTag>();
Parts = new HashSet<Part>();
}
public int ID { get; set; }
public virtual ICollection<NoteTag> NoteTags { get; set; }
public virtual ICollection<Part> Parts { get; set; }
public DateTime? CreationDate { get; set; }
[NotMapped]
public string TagsToAdd { get; set; }
[NotMapped]
public string TagsAsSingleString {
get
{
string result = "";
foreach(var nt in NoteTags)
{
result += nt.Tag.Name + " ";
}
return result;
}
}
}
public class NoteTag
{
public int NoteId { get; set; }
public virtual Note Note { get; set; }
public int TagId { get; set; }
public virtual Tag Tag { get; set; }
}
When I try to get data using this WebAPI controller, I get 502 bad gateway. No errors, everything's fine while debugging server. Data get from database correctly.
I suspect that it could be something similar to "infinite loop" but how to prevent it? (Note class is connected to collection of NoteTag objects that are connected back to Note which probably makes this loop).
And why there are no errors if something went wrong? :/
I don't know if it still relevant but i had the same problem and what worked for me it to Configure Newtonsoft.Json
SerializerSettings.ReferenceLoopHandling = ewtonsoft.Json.ReferenceLoopHandling.Ignore.
If you are using VS2015 MVC you can add the following code:
services.AddMvc().AddJsonOptions(options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore);
in the ConfigureServices method in the Startup class.
I think the problem its recursion, can you try with an Anonymous type
NoteTags has Note , imagine if the Note->NoteTags->Note->NoteTags->Note->NoteTags ...
`List n = db.Notes.Include(x => x.NoteTags).ToList();
var e = n.select(x=> new {property=value});
result = Json(e);`

method declared as public not found

In my common.cs class I have the below declarations for a list based on a class:
public static List<edbService> edb_service;
public class edbService
{
public string ServiceID { get; set; }
public string ServiceName { get; set; }
public string ServiceDescr { get; set; }
public string ServiceInterval { get; set; }
public string ServiceStatus { get; set; }
public string ServiceUrl { get; set; }
public string SourceApplication { get; set; }
public string DestinationApplication { get; set; }
public string Function { get; set; }
public string Version { get; set; }
public string userid { get; set; }
public string credentials { get; set; }
public string orgid { get; set; }
public string orgunit { get; set; }
public string customerid { get; set; }
public string channel { get; set; }
public string ip { get; set; }
}
I have a public method to populate the list from xml data files declared like this in the same class (common.cs):
#region PublicMethods
public List<edbService> populateEDBService(string xmlDataFile)
{
try
{
XElement x = XElement.Load(global::EvryCardManagement.Properties.Settings.Default.DataPath + xmlDataFile);
// Get global settings
IEnumerable<XElement> services = from el in x.Descendants("Service")
select el;
if (services != null)
{
edb_service = new List<edbService>();
foreach (XElement srv in services)
{
edbService edbSrv = new edbService();
edbSrv.ServiceID = srv.Element("ServiceID").Value;
edbSrv.ServiceName = srv.Element("ServiceName").Value;
edbSrv.ServiceDescr = srv.Element("ServiceDescr").Value;
edbSrv.ServiceInterval = srv.Element("ServiceInterval").Value;
edbSrv.ServiceStatus = srv.Element("ServiceStatus").Value;
edbSrv.ServiceUrl = srv.Element("ServiceUrl").Value;
foreach (XElement ServiceHeader in srv.Elements("ServiceHeader"))
{
edbSrv.SourceApplication = ServiceHeader.Element("SourceApplication").Value;
edbSrv.DestinationApplication = ServiceHeader.Element("DestinationApplication").Value;
edbSrv.Function = ServiceHeader.Element("Function").Value;
edbSrv.Version = ServiceHeader.Element("Version").Value;
foreach (XElement ClientContext in ServiceHeader.Elements("ClientContext"))
{
edbSrv.userid = ClientContext.Element("userid").Value;
edbSrv.credentials = ClientContext.Element("credentials").Value;
edbSrv.orgid = ClientContext.Element("orgid").Value;
edbSrv.orgunit = ClientContext.Element("orgunit").Value;
edbSrv.customerid = ClientContext.Element("customerid").Value;
edbSrv.channel = ClientContext.Element("channel").Value;
edbSrv.ip = ClientContext.Element("ip").Value;
}
}
edb_service.Add(edbSrv);
}
}
}
catch (Exception ex)
{
/* Write to log */
Common.logBuilder("CustomerCreate : Form --> CustomerCreate <--", "Exception", Common.ActiveMQ,
ex.Message, "Exception");
/* Send email to support */
emailer.exceptionEmail(ex);
}
return edb_service;
}
but the problem is, in my calling class when I try to have a list returned from this method, it is not found - I get a compile error that an object reference is required.
I am trying to call it like this:
Common.edbService edb_service = Common.populateEDBService("CardUpdate.xml");
and I get the below error:
An object reference is required for the non-static field, method, or property 'EvryCardManagement.Common.populateEDBService(string)'
What am I doing wrong?
I would like to have a generic method that can be called from several classes (which run async after being instantiated by background workers on my form)
You can try making your method as static.
public static List<edbService> populateEDBService(string xmlDataFile)
{
//Your code here
....
}
Now you can call this method from all the other classes by using common.populateEDBService();
You need either to create the class static, or to create an object to call it.
class edbService { }
public static void Main() {
//this is error
edbService.populateEDBService("");
//this is correct
edbService s = new edbService();
s.populateEDBService("");
}
The last line in my example shows the object reference required by the compiler. The s variable here is the object reference.
Are there any missing values in your XML? The.Value property won't work if the value is missing. So if ServiceID is missing then srv.Element("ServiceID").Value; will cause an error. You can get it to return an empty string for missing values, for example, by instead using (string)srv.Element("ServiceID");

Error inserting record with entity framework

I am sorry if it has already been answered but I can't find any solution. Here is my (little) problem. Also all my apologies if the terms I use are approximate, I am far from being a skilled C# developer
Note that I think my problem is similar to this one Entity Framework validation error for missing field, but it's not missing?
I have a table "Tweets" with a tweet_id field (bigint) which is my primary key.
I use the following class to load the table :
class TwitterDbContext : DbContext
{
public TwitterDbContext() : base("Twitter")
{
}
public DbSet<Stream> Streams { get; set; }
public DbSet<StreamParameter> StreamParameters { get; set; }
public DbSet<Tweet> Tweets { get; set; }
}
public class Tweet
{
public Tweet()
{
}
[Key]
public long tweet_id { get; set; }
public string tweet { get; set; }
public long creator { get; set; }
public double latitude { get; set; }
public double longitude { get; set; }
public string language { get; set; }
public DateTime created_at { get; set; }
public DateTime registered_at { get; set; }
public long? in_reply_to { get; set; }
public bool retweeted { get; set; }
}
I have an other class to store within the code execution all the fields used by the Tweet table. For the need here, let's imagine I manually create it that way
private void Test_Button_Click(object sender, RoutedEventArgs e)
{
Twts twtReceived = new Twts();
twtReceived.tweet_id = 1;
twtReceived.tweet = "test";
twtReceived.creator = 1;
twtReceived.latitude = -1;
twtReceived.longitude = -1;
twtReceived.language = "a";
twtReceived.created_at = DateTime.Now;
twtReceived.registered_at = DateTime.Now;
twtReceived.in_reply_to = 1;
twtReceived.retweeted = true;
AddTweet(twtReceived);
}
Now here is the AddTweet method
static public void AddTweet(Twts twtReceived)
{
try
{
// update the tweet data in the database
using (var TwitterDb = new TwitterDbContext())
{
Tweet twt = new Tweet()
{
tweet_id = twtReceived.tweet_id,
tweet = twtReceived.tweet,
creator = twtReceived.creator,
longitude = twtReceived.longitude,
latitude = twtReceived.latitude,
language = twtReceived.language,
created_at = twtReceived.created_at,
registered_at = twtReceived.registered_at,
in_reply_to = twtReceived.in_reply_to,
retweeted = twtReceived.retweeted
};
TwitterDb.Tweets.Add(twt);
TwitterDb.SaveChanges();
}
}
catch(Exception ex)
{
MessageBox.Show(ex.InnerException.ToString());
}
}
I constantly have the same error message:
Cannot insert the value NULL into column 'tweet_id', table
'Twitter.dbo.Tweets'; column does not allow nulls. INSERT fails.
The thing is that when I spy on "TwitterDb.Tweets.Local" after TwitterDb.Tweets.Add(twt); I correctly have tweet_id set to 1.
Any idea where is the issue?
Try marking your tweet_id field with following (instead of just [Key]), if this is a primary key column where you want to provide values yourself
[Required, Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
If it is an auto-increment, then remove explicit assignments to this field and mark it as 'Identity' instead:
[Required, Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]

Categories

Resources