Why my ICollection is always empty? - c#

I am trying to reach a foreach but my program never gets inside because my ICollection Coletores is always empty even if I put a lot of stuff in there.
The code where I want to get inside and it is always empty (I want to get inside the second foreach):
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
if (NavigationContext.QueryString.TryGetValue("email", out email))
{
//MessageBox.Show(email);
List<HyperlinkButton> listaLinks = new List<HyperlinkButton>();
AppDataContext db = new AppDataContext();
int i = 0;
HyperlinkButton aux = new HyperlinkButton();
foreach (Pessoa pessoa in db.Pessoas)
{
if (pessoa.Email == email)
{
foreach (Coletor coletor in pessoa.Coletores)
{
aux.Content = "Coletor " + (i + 1).ToString();
aux.FontSize = 24;
aux.NavigateUri = new Uri("/OcorrenciasPage.xaml?coletorId=" + coletor.Id.ToString(), UriKind.RelativeOrAbsolute);
listaLinks.Add(aux);
i++;
}
}
}
ListBox coletores = new ListBox();
coletores.ItemsSource = listaLinks;
stcList.Children.Add(coletores);
}
base.OnNavigatedTo(e);
}
Now the code that I am adding data:
if (txtLat.Text != "" && txtLong.Text != "" && rdNorte.IsChecked == true || rdSul.IsChecked == true && rdLeste.IsChecked == true || rdOeste.IsChecked == true)
{
foreach (var pessoa in db.Pessoas)
{
if (pessoa.Email == email)
{
pessoa.Coletores.Add(coletor);
}
}
db.Coletores.InsertOnSubmit(coletor);
db.SubmitChanges();
NavigationService.Navigate(new Uri("/ColetoresPage.xaml?email=" + email, UriKind.RelativeOrAbsolute));
}
Now, my Pessoa class:
public class Pessoa : INotifyPropertyChanged
{
private int _id;
[Column(IsDbGenerated = true, IsPrimaryKey = true)]
public int Id {
get { return _id;}
set { _id = value;
OnPropertyChanged("Id");
}
}
private string _nome;
[Column]
public string Nome
{
get { return _nome; }
set { _nome = value;
OnPropertyChanged("Nome");
}
}
private string _email;
[Column]
public string Email
{
get { return _email; }
set { _email = value;
OnPropertyChanged("Email");
}
}
private string _senha;
[Column]
public string Senha { get { return _senha; }
set { _senha = value;
OnPropertyChanged("Senha");
}
}
private string _profissao;
[Column]
public string Profissao { get { return _profissao; }
set { _profissao = value;
OnPropertyChanged("Profissao");
}
}
private int _idade;
[Column]
public int Idade { get { return _idade; }
set { _idade = value;
OnPropertyChanged("Idade");
}
}
private string _endereco;
[Column]
public string Endereco { get { return _endereco; }
set { _endereco = value;
OnPropertyChanged("Endereco");
}
}
private string _cidade;
[Column]
public string Cidade { get { return _cidade; }
set { _cidade = value;
OnPropertyChanged("Cidade");
}
}
private string _estado;
[Column]
public string Estado { get { return _estado; }
set { _estado = value;
OnPropertyChanged("Estado");
}
}
private EntitySet<Coletor> _coletores = new EntitySet<Coletor>();
[Association(Name = "FK_Coletores_PessoaColetores", Storage = "_coletores", ThisKey = "Id", OtherKey = "pessoaId")]
public ICollection<Coletor> Coletores
{
get { return _coletores; }
set { _coletores.Assign(value); }
}
private EntitySet<PessoaColetor> _pessoaColetores = new EntitySet<PessoaColetor>();
[Association(Name = "FK_PessoaColetores_Pessoas", Storage = "_pessoaColetores", OtherKey = "pessoaId", ThisKey = "Id")]
private ICollection<PessoaColetor> PessoaColetores
{
get { return _pessoaColetores; }
set { _pessoaColetores.Assign(value); }
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string name)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(name));
}
}
}

The Coletores property on the Pessoa class looks alright. There is also a PessoaColetores property. Are you sure there has been no confusion between the two? Especially with intellisense one might dot or tab the wrong one.
Have you put a break point on the line that actually adds coletors (second code snippet)? Maybe stuff is added to the wrong collection.
Cheers, B.

Related

json DeserializeObject ArgumentException

I am trying to Serialize/Deserialize a object, but I am getting an "ArgumentException" on deserialization.
My Object is this:
public class Findoc
{
public Findoc()
{
}
private string _ID = string.Empty;
public string ID
{
get { return this._ID; }
set { _ID = value; }
}
private int _lastindex;
public int lastindex
{
get { return this._lastindex; }
set { _lastindex = value; }
}
private string _SilogiDate;
public string SilogiDate
{
get { return this._SilogiDate; }
set { _SilogiDate = value; }
}
private Truck _TR;
public Truck TR
{
get { return this._TR; }
set { _TR = value; }
}
private Routing _RT;
public Routing RT
{
get { return this._RT; }
set { _RT = value; }
}
private KentroKostous _KK;
public KentroKostous KK
{
get { return this._KK; }
set { _KK = value; }
}
private Busunit _BU;
public Busunit BU
{
get { return this._BU; }
set { _BU = value; }
}
private string _FINCODE = string.Empty;
public string FINCODE
{
get { return this._FINCODE; }
set { _FINCODE = value; }
}
private string _FINSTATE = "";
public string FINSTATE
{
get { return this._FINSTATE; }
set { _FINSTATE = value; }
}
private string _STAGE = "";
public string STAGE
{
get { return this._STAGE; }
set { _STAGE = value; }
}
private string _SPCS = "";
public string SPCS
{
get { return this._SPCS; }
set { _SPCS = value; }
}
private string _SPCSCODE = "";
public string SPCSCODE
{
get { return this._SPCSCODE; }
set { _SPCSCODE = value; }
}
private string _MTRSTS = "";
public string MTRSTS
{
get { return this._MTRSTS; }
set { _MTRSTS = value; }
}
private string _PARAGOMENO = "";
public string PARAGOMENO
{
get { return this._PARAGOMENO; }
set { _PARAGOMENO = value; }
}
private double _PARAGOMENOQTY1;
public double PARAGOMENOQTY1
{
get { return this._PARAGOMENOQTY1; }
set { _PARAGOMENOQTY1 = value; }
}
private double _PARAGOMENOQTY2;
public double PARAGOMENOQTY2
{
get { return this._PARAGOMENOQTY2; }
set { _PARAGOMENOQTY2 = value; }
}
private Boolean _PARAGOMENOUSESN;
public Boolean PARAGOMENOUSESN
{
get { return this._PARAGOMENOUSESN; }
set { _PARAGOMENOUSESN = value; }
}
private Boolean _EDITABLE = true;
public Boolean EDITABLE
{
get { return this._EDITABLE; }
set { _EDITABLE = value; }
}
private Boolean _ISPRINT;
public Boolean ISPRINT
{
get { return this._ISPRINT; }
set { _ISPRINT = value; }
}
private Boolean _ISCANCELED;
public Boolean ISCANCELED
{
get { return this._ISCANCELED; }
set { _ISCANCELED = value; }
}
private int _SOSOURCE;
public int SOSOURCE
{
get { return this._SOSOURCE; }
set { _SOSOURCE = value; }
}
private Series _series;
public Series Series
{
get { return this._series; }
set { _series = value; }
}
private string _TICK = string.Empty;
public string TICK
{
get { return this._TICK; }
set { _TICK = value; }
}
private string _COMMENTS = "";
public string COMMEMTS
{
get { return this._COMMENTS; }
set { _COMMENTS = value; }
}
private string _COMMENTS1 = "";
public string COMMEMTS1
{
get { return this._COMMENTS1; }
set { _COMMENTS1 = value; }
}
private string _COMMENTS2 = "";
public string COMMEMTS2
{
get { return this._COMMENTS2; }
set { _COMMENTS2 = value; }
}
private string _karfoto_fincode = "";//gia tis eisprakseis
public string Karfoto_fincode
{
get { return this._karfoto_fincode; }
set { _karfoto_fincode = value; }
}
private List<Mtrline> _Mtrlines;
public List<Mtrline> Mtrlines
{
get { return this._Mtrlines; }
set { _Mtrlines = value; }
}
}
public class SnLine
{
private string _TICK;
public string TICK
{
get { return this._TICK; }
set { _TICK = value; }
}
private string _sn;
public string sn
{
get { return this._sn; }
set { _sn = value; }
}
}
public class Mtrline
{
public Mtrline(Findoc findoc)
{
}
private List<SnLine> _SnLines;
public List<SnLine> SnLines
{
get { return this._SnLines; }
set { _SnLines = value; }
}
private int _position;
public int position
{
get { return this._position; }
set { _position = value; }
}
private string _guid;
public string guid
{
get { return this._guid; }
set { _guid = value; }
}
private WhouseObj _Whouse1;
public WhouseObj Whouse1
{
get { return this._Whouse1; }
set { _Whouse1 = value; }
}
private WhouseObj _Whouse2;
public WhouseObj Whouse2
{
get { return this._Whouse2; }
set { _Whouse2 = value; }
}
private string _WHOUSE = "";
public string WHOUSE
{
get { return this._WHOUSE; }
set { _WHOUSE = value; }
}
private string _WHOUSESEC = "";
public string WHOUSESEC
{
get { return this._WHOUSESEC; }
set { _WHOUSESEC = value; }
}
private string _SPCS;
public string SPCS
{
get { return this._SPCS; }
set { _SPCS = value; }
}
private string _MPKCODE;
public string MPKCODE
{
get { return this._MPKCODE; }
set { _MPKCODE = value; }
}
private string _whousebin1remain;
public string Whousebin1remain
{
get { return this._whousebin1remain; }
set { _whousebin1remain = value; }
}
private string _whousebin2remain;
public string Whousebin2remain
{
get { return this._whousebin2remain; }
set { _whousebin2remain = value; }
}
private int _NEWLINE;
public int NEWLINE
{
get { return this._NEWLINE; }
set { _NEWLINE = value; }
}
private string _CCCPACK1;
public string CCCPACK1
{
get {
if (_CCCPACK1 == null)
return "";
else
return this._CCCPACK1;
}
set { _CCCPACK1 = value; }
}
public string _CCCPACK2;
public string CCCPACK2
{
get
{
if (_CCCPACK2 == null)
return "";
else
return this._CCCPACK2;
}
set { _CCCPACK2 = value; }
}
private string _PAKETO = "";
public string PAKETO
{
get { return this._PAKETO; }
set { _PAKETO = value; }
}
private string _TICK;
public string TICK
{
get { return this._TICK; }
set { _TICK = value; }
}
private string _AAA;
public string AAA
{
get { return this._AAA; }
set { _AAA = value; }
}
private MtrlModel _MTRL_Object;
public MtrlModel MTRL_Object
{
get { return this._MTRL_Object; }
set { _MTRL_Object = value; }
}
private double _SUMQTY; // SUMQTY ana eidos
public double SUMQTY
{
get { return this._SUMQTY; }
set { _SUMQTY = value; }
}
private double _SUMQTY2; // SUMQTY ana eidos
public double SUMQTY2
{
get { return this._SUMQTY2; }
set { _SUMQTY2 = value; }
}
private double _QTY; // posotita T
public double QTY
{
get { return this._QTY; }
set { _QTY = value; }
}
private double _QTY1;
public double QTY1
{
get { return this._QTY1; }
set { _QTY1 = value; }
}
private double _QTY2;
public double QTY2
{
get { return this._QTY2; }
set { _QTY2 = value; }
}
private double _QTYP;
public double QTYP
{
get { return this._QTYP; }
set { _QTYP = value; }
}
private string _FIELDS = "";
public string FIELDS
{
get { return this._FIELDS; }
set { _FIELDS = value; }
}
private string _COMMENTS = "";
public string COMMENTS
{
get { return this._COMMENTS; }
set { _COMMENTS = value; }
}
private string _COMMENTS1 = "";
public string COMMENTS1
{
get { return this._COMMENTS1; }
set { _COMMENTS1 = value; }
}
private string _COMMENTS2 = "";
public string COMMENTS2
{
get { return this._COMMENTS2; }
set { _COMMENTS2 = value; }
}
private CDIMLINE _CDIMNO1_Object;
public CDIMLINE CDIMNO1_Object
{
get { return this._CDIMNO1_Object; }
set { _CDIMNO1_Object = value; }
}
private string _CDIMNO1;
public string CDIMNO1
{
get
{
if (this._CDIMNO1_Object != null)
return this._CDIMNO1_Object.NAME;
else
return "";
}
set { _CDIMNO1 = value; }
}
private CDIMLINE _CDIMNO2_Object;
public CDIMLINE CDIMNO2_Object
{
get { return this._CDIMNO2_Object; }
set { _CDIMNO2_Object = value; }
}
private string _CDIMNO2;
public string CDIMNO2
{
get
{
if (this._CDIMNO2_Object != null)
return this._CDIMNO2_Object.NAME;
else
return "";
}
set { _CDIMNO2 = value; }
}
private CDIMLINE _CDIMNO3_Object;
public CDIMLINE CDIMNO3_Object
{
get { return this._CDIMNO3_Object; }
set { _CDIMNO3_Object = value; }
}
private string _CDIMNO3;
public string CDIMNO3
{
get
{
if (this._CDIMNO3_Object != null)
return this._CDIMNO3_Object.NAME;
else
return "";
}
set { _CDIMNO3 = value; }
}
private Lot _LOT;
public Lot LOT
{
get { return this._LOT; }
set { _LOT = value; }
}
private string _CODE = "";
public string CODE
{
get { return this._MTRL_Object.CODE; }
set { _CODE = value; }
}
private string _MTRPLACE = "";
public string MTRPLACE
{
get { return this._MTRL_Object.MTRPLACE; }
set { _MTRPLACE = value; }
}
private double _SUMWHOUSE;
public double SUMWHOUSE
{
get { return this._MTRL_Object.REMAIN; }
set { _SUMWHOUSE = value; }
}
private double _WHOUSE_SERIES;
public double WHOUSE_SERIES
{
get { return this._MTRL_Object.WHOUSE_SERIES_REMAIN; }
set { _WHOUSE_SERIES = value; }
}
private string _CODE1 = "";
public string CODE1
{
get { return this._MTRL_Object.CODE1; }
set { _CODE1 = value; }
}
private string _CODE2 = "";
public string CODE2
{
get { return this._MTRL_Object.CODE2; }
set { _CODE2 = value; }
}
private string _NAME = "";
public string NAME
{
get { return this._MTRL_Object.NAME; }
set { _NAME = value; }
}
private string _MTRL = "";
public string MTRL
{
get { return this._MTRL_Object.MTRL; }
set { _MTRL = value; }
}
private string _MTRUNIT1 = "";
public string MTRUNIT1
{
get
{
if (this._MTRL_Object.MTRUNIT1 != null)
return this._MTRL_Object.MTRUNIT1.name;
else
return "";
}
set { _MTRUNIT1 = value; }
}
private string _MTRUNIT2 = "";
public string MTRUNIT2
{
get
{
if (this._MTRL_Object.MTRUNIT2 != null)
return this._MTRL_Object.MTRUNIT2.name;
else
return "";
}
set { _MTRUNIT2 = value; }
}
private string _MTRUNIT3 = "";
public string MTRUNIT3
{
get
{
if (this._MTRL_Object.MTRUNIT3 != null)
return this._MTRL_Object.MTRUNIT3.name;
else
return "";
}
set { _MTRUNIT3 = value; }
}
private string _MTRUNIT4 = "";
public string MTRUNIT4
{
get
{
if (this._MTRL_Object.MTRUNIT4 != null)
return this._MTRL_Object.MTRUNIT4.name;
else
return "";
}
set { _MTRUNIT4 = value; }
}
private string _CRLOTCODE = "";
public string CRLOTCODE
{
get { return this._CRLOTCODE; }
set { _CRLOTCODE = value; }
}
private string _CRLOTCODE1 = "";
public string CRLOTCODE1
{
get { return this._CRLOTCODE1; }
set { _CRLOTCODE1 = value; }
}
private string _CRLOTCODE2 = "";
public string CRLOTCODE2
{
get { return this._CRLOTCODE2; }
set { _CRLOTCODE2 = value; }
}
private string _CRLOTFDATE = "";
public string CRLOTFDATE
{
get { return this._CRLOTFDATE; }
set { _CRLOTFDATE = value; }
}
private string _SCANEDCODE = "";
public string SCANEDCODE
{
get { return this._SCANEDCODE; }
set { _SCANEDCODE = value; }
}
private Thesi _WHOUSEBIN1_Object;
public Thesi WHOUSEBIN1_Object
{
get { return this._WHOUSEBIN1_Object; }
set { _WHOUSEBIN1_Object = value; }
}
private string _WHOUSEBIN1;
public string WHOUSEBIN1
{
get
{
if (this._WHOUSEBIN1_Object != null)
return this._WHOUSEBIN1_Object.name;
else
return "";
}
set { _WHOUSEBIN1 = value; }
}
private Thesi _WHOUSEBIN2_Object;
public Thesi WHOUSEBIN2_Object
{
get { return this._WHOUSEBIN2_Object; }
set { _WHOUSEBIN2_Object = value; }
}
private string _WHOUSEBIN2;
public string WHOUSEBIN2
{
get
{
if (this._WHOUSEBIN2_Object != null)
return this._WHOUSEBIN2_Object.name;
else
return "";
}
set { _WHOUSEBIN2 = value; }
}
private double _ANAMENOMENA;
public double ANAMENOMENA
{
get { return this._ANAMENOMENA; }
set { _ANAMENOMENA = value; }
}
private string _FINCODE = "";
public string FINCODE
{
get { return this._FINCODE; }
set { _FINCODE = value; }
}
private string _FINDOC = "";
public string FINDOC
{
get { return this._FINDOC; }
set { _FINDOC = value; }
}
private string _SODTYPE = "";
public string SODTYPE
{
get { return this._SODTYPE; }
set { _SODTYPE = value; }
}
private string _STATUS = "";
public string STATUS
{
get { return this._STATUS; }
set { _STATUS = value; }
}
private string _AA = "";
public string AA
{
get { return this._AA; }
set { _AA = value; }
}
private string _GUARANTY_SNCODE = "";
public string GUARANTY_SNCODE
{
get { return this._GUARANTY_SNCODE; }
set { _GUARANTY_SNCODE = value; }
}
}
I serialize it with the following code:
string data = Newtonsoft.Json.JsonConvert.SerializeObject(UniversalModel.Parastatiko,Formatting.None , new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
When I try to deserialize back to the object I get the exception error: ArgumentException.
The code to deserialize is this.
Findoc FFF = Newtonsoft.Json.JsonConvert.DeserializeObject<Findoc>(data, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
Any tips on what I am doing wrong?
It may just be a typo in the question but separating the Serializer arguments on to their own lines shows you are passing a UniversalModel.Parastatiko in as the first argument...which I don't think is correct.
string data = Newtonsoft.Json.JsonConvert.SerializeObject(
UniversalModel.Parastatiko,
Formatting.None,
new JsonSerializerSettings {
NullValueHandling = NullValueHandling.Ignore
}
);

LINQ query does not return child fields

I think I'm getting stupid because I can't get my LINQ query to work as I expect. I have one class that has 3 relationships to other classes.
This is the main class
[Table(Name = "scanResult")]
public class SniffResult
{
public SniffResult()
{
}
public SniffResult(Address address)
{
this.address = address;
}
private int _pk_SniffResult;
[Column(IsPrimaryKey = true, IsDbGenerated = true, Storage = "_pk_SniffResult", Name ="pk_scanResult")]
public int pk_SniffResult { get { return _pk_SniffResult; } set { this._pk_SniffResult = value; } }
private int _fk_scan;
[Column(Storage = "_fk_scan", Name = "scan")]
public int fk_scan { get { return _fk_scan; } set { this._fk_scan = value; } }
private Scan _scan;
[Association(Storage = "_scan", IsForeignKey = true, ThisKey = "fk_scan", OtherKey = "pk_scan")]
public Scan scan { get { return _scan; } set { this._scan = value; } }
private int _fk_address;
[Column(Storage = "_fk_address", Name = "address")]
public int fk_adress { get { return _fk_address; } set { this._fk_address = value; } }
private Address _address;
[Association(Storage ="_address", IsForeignKey = true, ThisKey = "fk_adress", OtherKey = "pk_address")]
public Address address { get { return _address; } set { this._address = value; } }
private string _rawResult;
[Column(Storage = "_rawResult", Name = "raw")]
public string rawResult { get { return _rawResult; } set { this._rawResult = value; } }
private int _code = -5;
[Column(Storage = "_code")]
public int code { get { return _code; } set { this._code = value; } }
private DateTime _scanDate = DateTime.Now;
[Column(Storage = "_scanDate")]
public DateTime scanDate { get { return _scanDate; } set { this._scanDate = value; } }
private int? _fk_proxy;
[Column(Storage = "_fk_proxy", Name = "usedProxy", CanBeNull = true)]
public int? fk_proxy { get { return _fk_proxy; } set { this._fk_proxy = value; } }
private ProxyData _usedProxy;
[Association(Storage = "_usedProxy", IsForeignKey = true, ThisKey = "fk_proxy", OtherKey = "pk_proxy")]
public ProxyData usedProxy { get { return _usedProxy; } set { this._usedProxy = value; } }
public string message { get; set; } = "";
public bool availability { get; set; }
public int planCode { get; set; }
public string planning { get; set; }
public override string ToString()
{
return string.Format("availability={0}, code={1}, message={2}", availability, code, message);
}
}
This is one of the child classes
[Table(Name = "address")]
public class Address
{
private int _pk_address;
[Column(IsPrimaryKey = true, IsDbGenerated = true, Storage = "_pk_address")]
public int pk_address { get { return _pk_address; } set { this._pk_address = value; } }
private string _provId;
[Column(Storage = "_provId")]
public string provId { get { return _provId; } set { this._provId = value; } }
private string _zipcode;
[Column(Storage = "_zipcode")]
public string zipcode { get { return _zipcode; } set { this._zipcode = value; } }
private int _houseNumber;
[Column(Storage = "_houseNumber")]
public int houseNumber { get { return _houseNumber; } set { this._houseNumber = value; } }
private string _addressAddition;
[Column(Storage = "_addressAddition")]
public string addressAddition { get { return _addressAddition; } set { this._addressAddition = value; } }
public string ToAddresString()
{
return string.Format("{0} {1}{2}", this.provId, zipcode, houseNumber, addressAddition);
}
public override string ToString()
{
return string.Format("{0}:\t{1}\t{2}{3}", this.provId, zipcode, houseNumber, addressAddition);
}
}
I want to get SniffResult including the associated fields. But they are all null. This is the code I use:
SniffDAO dao = new SniffDAO();
var test = from sr in dao.SniffResults
where sr.fk_scan == 3
select sr;
foreach (var one in test)
{
Console.WriteLine(one.pk_SniffResult);
Console.WriteLine(one.address);
}
one.address gives me a null, what am I doing wrong?
This is the Dao class
public class SniffDAO
{
private string currentDir;
private DataContext db;
public Table<Scan> Scans { get; set; }
public Table<SniffResult> SniffResults { get; set; }
public Table<Address> Addresses { get; set; }
public SniffDAO()
{
db = new DataContext(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=********;Integrated Security=True;Asynchronous Processing=True");
db.ObjectTrackingEnabled = true;
Scans = db.GetTable<Scan>();
SniffResults = db.GetTable<SniffResult>();
Addresses = db.GetTable<Address>();
currentDir = Directory.GetCurrentDirectory();
}
public void save()
{
db.SubmitChanges();
}
}
You need to Include related entities like this:
SniffDAO dao = new SniffDAO();
var test = dao.SniffResults.Include(x=>x.address).Where(sr.fk_scan == 3);
foreach (var one in test)
{
Console.WriteLine(one.pk_SniffResult);
Console.WriteLine(one.address);
}
I found the solution thanks to #Kris. I now use:
DataLoadOptions dlo = new DataLoadOptions();
dlo.LoadWith<SniffResult>(sr => sr.address);
dlo.LoadWith<SniffResult>(sr => sr.usedProxy);
dlo.LoadWith<SniffResult>(sr => sr.scan);
db.LoadOptions = dlo; //db is the DataContext
See https://msdn.microsoft.com/en-us/library/bb548760(v=vs.110).aspx for more info

C# LINQ to SQL Invalid Object Name

public class AMCOMDB : DataContext
{
public Table<student> allStudents;
public Table<aClass> allClasses;
public AMCOMDB(string connection) : base(connection) { }
}
[Table(Name = "student")]
public class student
{
private string _studentName;
[Column(IsPrimaryKey =true,Storage ="_studentName")]
public string studentName
{
get { return this._studentName; }
set { this._studentName = value; }
}
private string _LARType;
[Column(Storage ="_LARType")]
public string LARType
{
get { return this._LARType; }
set { this._LARType = value; }
}
private string _studentType;
[Column(Storage = "_studentType")]
public string studentType
{
get { return this._studentType; }
set { this._studentType = value; }
}
private string _aviationLevel;
[Column(Storage = "_aviationLevel")]
public string aviationLevel
{
get { return this._aviationLevel; }
set { this._aviationLevel = value; }
}
private string _airDefenseLevel;
[Column(Storage = "_airDefenseLevel")]
public string airDefenseLevel
{
get
{
return this._airDefenseLevel;
}
set
{
this._airDefenseLevel = value;
}
}
private string _emergencyContact;
[Column(Storage = "_emergencyContact")]
public string emergencyContact
{
get
{
return this._emergencyContact;
}
set
{
this._emergencyContact = value;
}
}
[Table(Name = "grades")]
public class grades
{
private string _studentName;
[Column(IsPrimaryKey = true, Storage = "_studentName")]
public string studentName
{
get
{
return this._studentName;
}
set
{
this._studentName = value;
}
}
private int _ET;
[Column(Storage = "_ET")]
public int ET
{
get
{
return this._ET;
}
set
{
this._ET = value;
}
}
private int _CP;
[Column(Storage = "_CP")]
public int CP
{
get
{
return this._CP;
}
set
{
this._CP = value;
}
}
private int _SB;
[Column(Storage = "_SB")]
public int SB
{
get
{
return this._SB;
}
set
{
this._SB = value;
}
}
private int _EC;
[Column(Storage = "_EC")]
public int EC
{
get
{
return this._EC;
}
set
{
this._EC = value;
}
}
private int _finalGrade;
[Column(Storage = "_finalGrade")]
public int finalGrade
{
get
{
return this._finalGrade;
}
set
{
this._finalGrade = value;
}
}
}
[Table(Name = "classes")]
public class aClass
{
private string _classNumber;
[Column(IsPrimaryKey = true, Storage = "_classNumber")]
public string classNumber
{
get
{
return this._classNumber;
}
set
{
this._classNumber = value;
}
}
private string _courseSeries;
[Column(Storage = "_courseSeries")]
public string courseSeries
{
get
{
return this._courseSeries;
}
set
{
this._courseSeries = value;
}
}
private string _courseNumber;
[Column(Storage = "_courseNumber")]
public string courseNumber
{
get
{
return this._courseNumber;
}
set
{
this._courseNumber = value;
}
}
private string _distanceLearning;
[Column(Storage = "_distanceLearning")]
public string distanceLearning
{
get
{
return this._distanceLearning;
}
set
{
this._distanceLearning = value;
}
}
private string _classStartDate;
[Column(Storage = "_classStartDate")]
public string classStartDate
{
get
{
return this._classStartDate;
}
set
{
this._classStartDate = value;
}
}
private string _classEndDate;
[Column(Storage = "_classEndDate")]
public string classEndDate
{
get
{
return this._classEndDate;
}
set
{
this._classEndDate = value;
}
}
private string _primaryInstructor;
[Column(Storage = "_primaryInstructor")]
public string primaryInstructor
{
get
{
return this._primaryInstructor;
}
set
{
this._primaryInstructor = value;
}
}
private string _secondaryInstructor;
[Column(Storage = "_secondaryInstructor")]
public string secondaryInstructor
{
get
{
return this._secondaryInstructor;
}
set
{
this._secondaryInstructor = value;
}
}
private string _location;
[Column(Storage = "_location")]
public string location
{
get
{
return this._location;
}
set
{
this._location = value;
}
}
private string _TDYCosts;
[Column(Storage = "_TDYCosts")]
public string TDYCosts
{
get
{
return this._TDYCosts;
}
set
{
this._TDYCosts = value;
}
}
private string _studentCount;
[Column(Storage = "_studentCount")]
public string studentCount
{
get
{
return this._studentCount;
}
set
{
this._studentCount = value;
}
}
private List<grades> _classGrades;
[Column(Storage = "_classGrades")]
public List<grades> classGrades
{
get
{
return this._classGrades;
}
set
{
this._classGrades = value;
}
}
AMCOMDB ADB = new AMCOMDB(connectionString);
if (ADB.DatabaseExists())
{
var stud = ADB.GetTable<student>();
var clas = ADB.GetTable<aClass>();
IQueryable<string> query = from c in stud
where c.studentName.Length > 5
orderby c.studentName.Length
select c.studentName.ToUpper();
foreach (string name in query)
{
}
//var q = from a in ADB.GetTable<student>()
// select a;
//dtStudents = LinqQuerytoDataTable(q);
//var q1 = from a in ADB.GetTable<aClass>()
// select a;
//aClass c = new aClass();
//dtClasses = reformatDataTable(q1);
}
I receive the following when I try to get information from the database at (foreach (string name in query))
An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Additional information: Invalid object name 'student'.
I also get this when I first create the database:
An unhandled exception of type 'System.InvalidOperationException' occurred in System.Data.Linq.dll
Additional information: Unable to determine SQL type for 'System.Collections.Generic.List`1[WindowsFormsApplication1.Form1+grades]'.
remove the word Name that is what worked for me
[Table("student")]
public class student

Entity Framework 6.1: CRUD on Child objects

I populate a data grid with a list of objects that come from a repository like this:
public static IEnumerable<Order> GetOrdersForDataGrid()
{
IEnumerable<Order> query;
using (RSDContext = new RSDContext())
{
query = context.Orders.Include(o=>o.OrderDetails).ToList();
}
return query;
}
When I want to edit an order I pass the selected row to a new window like this:
OrderEditWindow orderEdit = new OrderEditWindow();
orderEdit.SelectedOrder = SelectedOrder;
orderEdit.ShowDialog();
Here I set the DataContext of the Window to:
DataContext = SelectedOrder;
In this window I have another data grid that binds to OrderDetails collection property of Order. The problem is on CRUD operations on OrderDetails. For example, after I add a new orderDetail like this:
private void AddProductDetailButton_OnClick(object sender, RoutedEventArgs e)
{
if (!ValidateProductDetail())
return;
var _selectedProduct = ProductAutoCompleteBox.SelectedItem as Product;
var selectedProduct = ProductsRepository.GetProductById(_selectedProduct.ProductId);
OrderDetail orderDetail = new OrderDetail();
orderDetail.Price = selectedProduct.Price;
orderDetail.ProductCode = selectedProduct.Code;
orderDetail.ProductName = selectedProduct.Name;
orderDetail.Quantity = int.Parse(QuantityNumericUpDown.Value.ToString());
orderDetail.Um = selectedProduct.Um;
orderDetail.Total = selectedProduct.Price * int.Parse(QuantityNumericUpDown.Value.ToString());
orderDetail.Group = selectedProduct.Subgroup.Group.Name;
orderDetail.Subgroup = selectedProduct.Subgroup.Name;
orderDetail.SupplierName = selectedProduct.Supplier.Name;
//orderDetail.Order=SelectedOrder;
//orderDetail.OrderId = SelectedOrder.OrderId;
SelectedOrder.OrderDetails.Add(orderDetail);
ProductAutoCompleteBox.Text = string.Empty;
QuantityNumericUpDown.Value = 1;
ProductAutoCompleteBox.Focus();
}
and then I call the update method from repository:
public static void UpdateOrder(Order order)
{
using (RSDContext context = new RSDContext())
{
context.Orders.Attach(order);
context.Entry(order).State = EntityState.Modified;
context.SaveChanges();
}
}
I get an error about OrderId. If i set manualy the navigation property and the id I don't get an error but changes dont get saved into db.
My Order model look like this:
public class Order : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public Order()
{
_OrderDetails = new ObservableCollection<OrderDetail>();
_OrderDetails.CollectionChanged += _OrderDetails_CollectionChanged;
}
void _OrderDetails_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
if (e.NewItems != null)
AttachProductChangedEventHandler(e.NewItems.Cast<OrderDetail>());
if (e.OldItems != null)
CalcualteTotals();
}
[NotMapped]
public decimal CalculatedTotal
{
get
{
return OrderDetails.Sum(x => x.Total);
}
}
public int OrderId { get; set; }
private int _Number;
public int Number
{
get { return _Number; }
set
{
_Number = value;
NotifyPropertyChanged("Number");
}
}
private DateTime _Date;
public DateTime Date
{
get { return _Date; }
set
{
_Date = value;
NotifyPropertyChanged("Date");
}
}
private bool _Canceled;
public bool Canceled
{
get { return _Canceled; }
set
{
_Canceled = value;
NotifyPropertyChanged("Canceled");
}
}
private string _ClientName;
public string ClientName
{
get { return _ClientName; }
set
{
_ClientName = value;
NotifyPropertyChanged("ClientName");
}
}
private string _ClientPhone;
public string ClientPhone
{
get { return _ClientPhone; }
set
{
_ClientPhone = value;
NotifyPropertyChanged("ClientPhone");
}
}
private string _DeliveryAddress;
public string DeliveryAddress
{
get { return _DeliveryAddress; }
set
{
_DeliveryAddress = value;
NotifyPropertyChanged("DeliveryAddress");
}
}
private decimal _Transport;
public decimal Transport
{
get { return _Transport; }
set
{
_Transport = value;
NotifyPropertyChanged("Transport");
}
}
private decimal _Total;
public decimal Total
{
get { return _Total; }
set
{
_Total = value;
NotifyPropertyChanged("Total");
}
}
private ObservableCollection<OrderDetail> _OrderDetails;
public virtual ObservableCollection<OrderDetail> OrderDetails
{
//get { return _OrderDetails ?? (_OrderDetails = new ObservableCollection<OrderDetail>()); }
get
{
return _OrderDetails;
}
set
{
_OrderDetails = value;
NotifyPropertyChanged("OrderDetails");
}
}
private void AttachProductChangedEventHandler(IEnumerable<OrderDetail> orderDetails)
{
foreach (var p in orderDetails)
{
p.PropertyChanged += (sender, e) =>
{
switch (e.PropertyName)
{
case "Quantity":
case "Price":
case "Total":
CalcualteTotals();
break;
}
};
}
CalcualteTotals();
}
public void CalcualteTotals()
{
NotifyPropertyChanged("CalculatedTotal");
}
public void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this,
new PropertyChangedEventArgs(propertyName));
}
}
}
And my OrderDetail model look like this:
public class OrderDetail : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public int OrderDetailId { get; set; }
public int OrderId { get; set; }
public Order Order { get; set; }
private int _ProductCode;
public int ProductCode
{
get { return _ProductCode; }
set
{
_ProductCode = value;
NotifyPropertyChanged("ProductCode");
}
}
private string _ProductName;
public string ProductName
{
get { return _ProductName; }
set
{
_ProductName = value;
NotifyPropertyChanged("ProductName");
}
}
private string _Um;
public string Um
{
get { return _Um; }
set
{
_Um = value;
NotifyPropertyChanged("Um");
}
}
private decimal _Price;
public decimal Price
{
get { return _Price; }
set
{
_Price = value;
NotifyPropertyChanged("Price");
NotifyPropertyChanged("Total");
}
}
private int _Quantity;
public int Quantity
{
get { return _Quantity; }
set
{
_Quantity = value;
NotifyPropertyChanged("Quantity");
NotifyPropertyChanged("Total");
}
}
private string _SupplierName;
public string SupplierName
{
get { return _SupplierName; }
set
{
_SupplierName = value;
NotifyPropertyChanged("SupplierName");
}
}
private string _Subgroup;
public string Subgroup
{
get { return _Subgroup; }
set
{
_Subgroup = value;
NotifyPropertyChanged("Subgroup");
}
}
private string _Group;
public string Group
{
get { return _Group; }
set
{
_Group = value;
NotifyPropertyChanged("Group");
}
}
public decimal _Total;
public decimal Total
{
get { return Quantity * Price; }
set
{
_Total = value;
NotifyPropertyChanged("Total");
}
}
public void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this,
new PropertyChangedEventArgs(propertyName));
}
}
}
I'm really trying to use some sort of unit of work and I don't understand how i'm supposed to apply CRUD on objects with child collections and keep the UI updated in the same time (by working in a ObservableCollection and using Binding ClientPhone, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged my parent window is updated as I type)
A final working solution:
using (RSDContext context = new RSDContext())
{
var details = order.OrderDetails;
order.OrderDetails = null;
List<int> OriginalOrderDetailsIds =
context.OrderDetails.Where(o => o.OrderId == order.OrderId).Select(o => o.OrderDetailId).ToList();
List<int> CurrentOrderDetailsIds = details.Select(o => o.OrderDetailId).ToList();
List<int> DeletedOrderDetailsIds = OriginalOrderDetailsIds.Except(CurrentOrderDetailsIds).ToList();
context.Entry(order).State = EntityState.Modified;
foreach (var deletedOrderDetailId in DeletedOrderDetailsIds)
{
context.Entry(context.OrderDetails.Single(o => o.OrderDetailId == deletedOrderDetailId)).State = EntityState.Deleted;
}
foreach (OrderDetail detail in details)
{
// Add.
if (detail.OrderDetailId == 0)
{
detail.OrderId = order.OrderId;
context.Entry(detail).State = EntityState.Added;
}
// Update.
else
{
context.Entry(detail).State = EntityState.Modified;
}
}
context.SaveChanges();
}
You could do this way for adding and updating the child, but not sure about deleted order details in the ui. If you don't want to get the order from entity, you need some kind of marking in the OrderDetail for deleted OrderDetail.
using (RSDContext context = new RSDContext())
{
var details = order.OrderDetails;
order.OrderDetails = null;
context.Entry(order).State = EntityState.Modified;
foreach (var detail in details)
{
if (detail.Id == 0)
{
// Adds.
detail.OrderId = order.Id;
context.Entry(detail).State = EntityState.Added;
}
else if (detail.IsDeleted)
// Adds new property called 'IsDeleted'
// and add [NotMapped] attribute
// then mark this property as true from the UI for deleted items.
{
// Deletes.
context.Entry(detail).State = EntityState.Deleted;
}
else
{
// Updates.
context.Entry(detail).State = EntityState.Modified;
}
}
order.OrderDetails = details;
context.SaveChanges();
}

string[] and string to DataGridView-Datasource

i have collection of class "Microsoft.Exchange.Management.TransportLogSearchTasks.MessageTrackingEvent"
this is microsoft class.
this class build like the following class
public class MTE
{
private DateTime timestamp;
private string clientIp;
private string clientHostname;
private string serverIp;
private string serverHostname;
private string sourceContext;
private string connectorId;
private string source;
private string eventId;
private string internalMessageId;
private string messageId;
private string[] recipients;
private string[] recipientStatus;
private int? totalBytes;
private int recipientCount;
private string relatedRecipientAddress;
private string[] reference;
private string messageSubject;
private string sender;
private string returnPath;
private string messageInfo;
private new DateTime Timestamp
{
get { return timestamp; }
set { timestamp = value; }
}
public new string ClientIp
{
get { return clientIp; }
set { clientIp = value; }
}
public new string ClientHostname
{
get { return clientHostname; }
set { clientHostname = value; }
}
public new string ServerIp
{
get { return serverIp; }
set { serverIp = value; }
}
public new string ServerHostname
{
get { return serverHostname; }
set { serverHostname = value; }
}
public new string SourceContext
{
get { return sourceContext; }
set { sourceContext = value; }
}
public new string ConnectorId
{
get { return connectorId; }
set { connectorId = value; }
}
public new string Source
{
get { return source; }
set { source = value; }
}
public new string EventId
{
get { return eventId; }
set { eventId = value; }
}
public new string InternalMessageId
{
get { return internalMessageId; }
set { internalMessageId = value; }
}
public new string MessageId
{
get { return messageId; }
set { messageId = value; }
}
public new string[] Recipients
{
get { return recipients; }
set { recipients = value; }
}
public new string RecipientStatus
{
get { return[] recipientStatus; }
set { recipientStatus = value; }
}
public new int? TotalBytes
{
get { return totalBytes; }
set { totalBytes = value; }
}
public new int RecipientCount
{
get { return recipientCount; }
set { recipientCount = value; }
}
public new string RelatedRecipientAddress
{
get { return relatedRecipientAddress; }
set { relatedRecipientAddress = value; }
}
public new string Reference
{
get { return[] reference; }
set { reference = value; }
}
public new string MessageSubject
{
get { return messageSubject; }
set { messageSubject = value; }
}
public new string Sender
{
get { return sender; }
set { sender = value; }
}
public new string ReturnPath
{
get { return returnPath; }
set { returnPath = value; }
}
public new string MessageInfo
{
get { return messageInfo; }
set { messageInfo = value; }
}
}
When i am doing
Collection<MTE> newMTE = new Collection<MTE>();
datagridview1.datasource= newMTE;
datagrid1.datasource = newMTE
on DGV i can see at all the string[] properties
on the datagrid i can see them but as property type and not as a value
image example:
http://farm6.staticflickr.com/5519/10725217114_226ddd96c7_m.jpg
my collection have millions of rows, so i need an easy to process solution.
thank you all for the help
newMTE is a collection itself and your string[] are collection of items too (string array).
You can use something like Grouping or Show Row Details to show subrows of a row.
Examples here:
http://www.wpftutorial.net/DataGrid.html

Categories

Resources