LINQ query does not return child fields - c#

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

Related

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

Why my ICollection is always empty?

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.

Wcf service saving changes to database using entity framework

I am trying to update/add data using wcf service and entity framework. I have 2 implementation of the same function. The first one is working perfectly. Here is the code for the first one:
public bool SaveEmployee(Employee employeeEntity)
{
Console.WriteLine("SaveEmployee has been executed");
using (var context = new iposEntities())
{
context.Database.Log = Console.Write;
using (var trans = context.Database.BeginTransaction())
{
try
{
if (employeeEntity.EmployeeID == 0)
{
context.employees.Add(new employee()
{
//EmployeeID=employeeEntity.EmployeeID,
NationalIDNo= employeeEntity.NationalIDNo,
FullNames= employeeEntity.FullNames,
Title = employeeEntity.Title.ToString(),
TitleOfCourtesy=employeeEntity.TitleOfCourtesy,
BirthDate=employeeEntity.BirthDate,
HireDate=employeeEntity.HireDate,
Address=employeeEntity.Address,
City=employeeEntity.City,
Phone=employeeEntity.Phone,
ReportsTo=employeeEntity.ReportsTo,
Salary=employeeEntity.Salary,
Password = employeeEntity.Password,
Status = Convert.ToSByte(employeeEntity.Status)
});
}
else
{
employee EmpEntity = context.employees.First(i => i.EmployeeID == employeeEntity.EmployeeID);
EmpEntity.NationalIDNo = employeeEntity.NationalIDNo;
EmpEntity.FullNames = employeeEntity.FullNames;
EmpEntity.Title = employeeEntity.Title.ToString();
EmpEntity.TitleOfCourtesy = employeeEntity.TitleOfCourtesy;
EmpEntity.BirthDate = employeeEntity.BirthDate;
EmpEntity.HireDate = employeeEntity.HireDate;
EmpEntity.Address = employeeEntity.Address;
EmpEntity.City = employeeEntity.City;
EmpEntity.Phone = employeeEntity.Phone;
EmpEntity.ReportsTo = employeeEntity.ReportsTo;
EmpEntity.Salary = employeeEntity.Salary;
EmpEntity.Password = employeeEntity.Password;
EmpEntity.Status = Convert.ToSByte(employeeEntity.Status);
context.Entry(EmpEntity).State = EntityState.Modified;
}
context.SaveChangesAsync();
trans.Commit();
}
catch (Exception ex)
{
trans.Rollback();
Console.WriteLine("An error occured during saving"+ex.Message);
}
}
}
return true;
}
The second implementation (which is not working) is here:
public bool SaveEmployee(Employee employeeEntity)
{
Console.WriteLine("SaveEmployee has been executed");
using (var context = new iposEntities())
{
context.Database.Log = Console.Write;
using (var trans = context.Database.BeginTransaction())
{
try
{
if (employeeEntity.EmployeeID == 0)
{
context.employees.Add(employeeEntity);
}
else
{
context.Entry(employeeEntity).State = EntityState.Modified;
}
context.SaveChangesAsync();
trans.Commit();
}
catch (Exception ex)
{
trans.Rollback();
Console.WriteLine("An error occured during saving"+ex.Message);
}
}
}
return true;
}
Here is a error message from Visual studio: Error 10 Argument 1: cannot convert from 'iPos.Interfaces.Employee' to 'iPos.Service.employee' C:\Dropbox\UniversalApp\iPos\iPos.Service\PosService.cs 241 51 iPos.Service
Please help what am i doing wrong? I believe my Employee POCO Class is Ok. Here is my POCO Class
public class Employee : IEditableObject, INotifyPropertyChanged
{
EmployeeData backupEmplData;
private int employeeID;
private string nationalIDNo;
private string fullNames;
private OccupationPositions title;
private string titleOfCourtesy;
private Nullable<System.DateTime> birthDate;
private Nullable<System.DateTime> hireDate;
private string address;
private string city;
private string phone;
private Nullable<int> reportsTo;
private Nullable<float> salary;
private string password;
private bool status;
private string photo;
public struct EmployeeData
{
internal int employeeID;
internal string nationalIDNo;
internal string fullNames;
internal OccupationPositions title;
internal string titleOfCourtesy;
internal Nullable<System.DateTime> birthDate;
internal Nullable<System.DateTime> hireDate;
internal string address;
internal string city;
internal string phone;
internal Nullable<int> reportsTo;
internal Nullable<float> salary;
internal string password;
internal bool status;
}
public Employee()
{
}
public enum OccupationPositions
{
GeneralEmployee,
CEO,
Casheer,
Accountant,
Foreperson,
InventoryOfficer,
StockManager,
supervisor,
Security,
SuppliesManager,
StaffManager,
HygeneStaff,
SalesRepresentative,
HR,
MarketingOfficer,
FinancialOfficer,
Receptionist,
MarketingManager,
PurchasingManager,
Consultant,
}
public Employee(int employeeID, string nationalIDNo, string fullNames, OccupationPositions title, string titleOfCourtesy, Nullable<System.DateTime> birthDate, Nullable<System.DateTime> hireDate, string address, string city, string phone, Nullable<int> reportsTo, Nullable<float> salary, string password, bool status)
{
this.backupEmplData = new EmployeeData();
backupEmplData.employeeID = employeeID;
EmployeeID = employeeID;
backupEmplData.nationalIDNo = nationalIDNo;
NationalIDNo = nationalIDNo;
backupEmplData.fullNames = fullNames;
FullNames = fullNames;
backupEmplData.title = title;
Title = title;
backupEmplData.titleOfCourtesy = titleOfCourtesy;
TitleOfCourtesy = titleOfCourtesy;
backupEmplData.birthDate = birthDate;
BirthDate = birthDate;
backupEmplData.hireDate = hireDate;
HireDate = hireDate;
backupEmplData.address = address;
Address = address;
backupEmplData.city = city;
City = city;
backupEmplData.phone = phone;
Phone = phone;
backupEmplData.reportsTo = reportsTo;
ReportsTo = reportsTo;
backupEmplData.password = password;
Password = password;
backupEmplData.status = status;
Status = status;
}
public void BeginEdit()
{
this.backupEmplData.employeeID = EmployeeID;
this.backupEmplData.nationalIDNo = NationalIDNo;
this.backupEmplData.fullNames = FullNames;
this.backupEmplData.title = Title;
this.backupEmplData.titleOfCourtesy = TitleOfCourtesy;
this.backupEmplData.birthDate = BirthDate;
this.backupEmplData.hireDate = HireDate;
this.backupEmplData.address = Address;
this.backupEmplData.city = City;
this.backupEmplData.phone = Phone;
this.backupEmplData.reportsTo = ReportsTo;
this.backupEmplData.salary = Salary;
this.backupEmplData.password = Password;
this.backupEmplData.status = Status;
}
public void CancelEdit()
{
EmployeeID=this.backupEmplData.employeeID;
NationalIDNo= this.backupEmplData.nationalIDNo;
FullNames= this.backupEmplData.fullNames;
Title= this.backupEmplData.title;
TitleOfCourtesy=this.backupEmplData.titleOfCourtesy;
BirthDate=this.backupEmplData.birthDate;
HireDate=this.backupEmplData.hireDate;
Address=this.backupEmplData.address;
City=this.backupEmplData.city;
Phone=this.backupEmplData.phone;
ReportsTo=this.backupEmplData.reportsTo;
Salary=this.backupEmplData.salary;
Password = this.backupEmplData.password;
Status = this.backupEmplData.status;
}
public void EndEdit()
{
this.backupEmplData.employeeID = EmployeeID;
this.backupEmplData.nationalIDNo=NationalIDNo;
this.backupEmplData.fullNames=FullNames;
this.backupEmplData.title=Title;
this.backupEmplData.titleOfCourtesy=TitleOfCourtesy;
this.backupEmplData.birthDate=BirthDate;
this.backupEmplData.hireDate=HireDate;
this.backupEmplData.address=Address;
this.backupEmplData.city=City;
this.backupEmplData.phone=Phone;
this.backupEmplData.reportsTo=ReportsTo;
this.backupEmplData.salary=Salary;
this.backupEmplData.password=Password;
this.backupEmplData.status = Status;
}
[DataMember(IsRequired = true)]
[Display(AutoGenerateField=false)]
public int EmployeeID
{
get
{
return employeeID;
}
set
{
employeeID = value;
NotifyPropertyChanged("EmployeeID");
}
}
[DataMember(IsRequired = true)]
[Required]
public string NationalIDNo {
get
{
return nationalIDNo;
}
set
{
nationalIDNo = value;
NotifyPropertyChanged("NationalIDNo");
}
}
[DataMember(IsRequired = true)]
[Required]
public string FullNames {
get
{
return fullNames;
}
set
{
fullNames = value;
NotifyPropertyChanged("FullNames");
}
}
[DataMember(IsRequired = true)]
[Required]
[Display(Name = "Position")]
public OccupationPositions Title
{
get
{
return title;
}
set
{
title = value;
NotifyPropertyChanged("Title");
}
}
[DataMember(IsRequired = true)]
public string TitleOfCourtesy {
get
{
return titleOfCourtesy;
}
set
{
titleOfCourtesy = value;
NotifyPropertyChanged("TitleOfCourtesy");
}
}
[DataMember(IsRequired = true)]
[Required]
public Nullable<System.DateTime> BirthDate {
get
{
return birthDate;
}
set
{
birthDate = value;
NotifyPropertyChanged("BirthDate");
}
}
[DataMember(IsRequired = true)]
[Required]
public Nullable<System.DateTime> HireDate {
get
{
return hireDate;
}
set
{
hireDate = value;
NotifyPropertyChanged("HireDate");
}
}
[DataMember(IsRequired = true)]
public string Address {
get
{
return address;
}
set
{
address = value;
NotifyPropertyChanged("Address");
}
}
[DataMember(IsRequired = true)]
public string City {
get
{
return city;
}
set
{
city = value;
NotifyPropertyChanged("City");
}
}
[DataMember(IsRequired = true)]
[Required]
public string Phone {
get
{
return phone;
}
set
{
phone = value;
NotifyPropertyChanged("Phone");
}
}
[DataMember(IsRequired = true)]
[Display(Name="On Contract")]
public bool Status
{
get
{
return status;
}
set
{
status = value;
NotifyPropertyChanged("Status");
}
}
[DataMember(IsRequired = true)]
[Display(AutoGenerateField = false)]
public Nullable<int> ReportsTo {
get
{
return reportsTo;
}
set
{
reportsTo = value;
NotifyPropertyChanged("ReportsTo");
}
}
[DataMember(IsRequired = true)]
public Nullable<float> Salary {
get
{
return salary;
}
set
{
salary = value;
NotifyPropertyChanged("Salary");
}
}
[DataMember(IsRequired = true)]
[Required]
public string Password {
get
{
return password;
}
set
{
password = value;
NotifyPropertyChanged("Password");
}
}
[DataMember(IsRequired = true)]
[Display(AutoGenerateField = false)]
public string Photo
{
get
{
return photo;
}
set
{
photo = value;
NotifyPropertyChanged("Photo");
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string info)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
}
Looks like you have 2 versions of Employee:
one in 'iPos.Interfaces.Employee'
another in 'iPos.Service.employee'
Even if they use the same source code, for the compiler they are 2 different classes.
Just use only one.

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

Getting StackOverflowException when setting property

public List<Empleado> ListarEmpleados()
{
List<Empleado> returnList = new List<Empleado>();
var lista = from u in DB.tabEmpleado
select new
{
u.idEmpleado,
u.idUsuario,
u.Nombre,
u.Apellidos,
u.Telefono1
};
foreach (var e in lista)
{
Empleado empleado = new Empleado();
empleado.idEmpleado = e.idEmpleado;
empleado.idUsuario = e.idUsuario;
empleado.nombre = e.Nombre;
empleado.apellidos = e.Apellidos;
empleado.telefono1 = e.Telefono1;
returnList.Add(empleado);
}
return returnList;
}
This is a WCF service, when is called it returns StackOverflow error in the class definition, exactly in the Set property of idEmpleado.
Class definition is here.
[DataContract]
public class Empleado
{
private int _idEmpleado;
[DataMember(IsRequired = false)]
public int idEmpleado
{
get { return _idEmpleado; }
set { idEmpleado = value; } ERROR
}
private int _idUsuario;
[DataMember(IsRequired = false)]
public int idUsuario
{
get { return _idUsuario; }
set { idUsuario = value; }
}
private string _nombre;
[DataMember(IsRequired = false)]
public string nombre
{
get { return _nombre; }
set { nombre = value; }
}
private string _apellidos;
[DataMember(IsRequired = false)]
public string apellidos
{
get { return _apellidos; }
set { apellidos = value; }
}
private string _telefono1;
[DataMember(IsRequired = false)]
public string telefono1
{
get { return _telefono1; }
set { telefono1 = value; }
}
}
}
Does anybody know where the error is?
Thanks in advance.
You are setting the value of the property by calling the property setter again, instead of directly setting its backing field. This causes an infinite recursion and a stack overflow as a result.
public int idEmpleado
{
get { return _idEmpleado; }
set { idEmpleado = value; } // SHOULD BE _idEmpleado = value
}

Categories

Resources