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
}
Related
I have a windows forms application where I have a views with multiple tables. The tables get built dynamically by setting the name of their columns by the properties of the object, and then adding them to the dataset. There's also an empty row added for each table. The issue I'm having is that out of the 9 objects being used to create these tables, 2 of the tables aren't getting any columns set or an empty row.
I've looked at the debug and have compared the objects properties that are getting columns to the one's without, and cannot decipher what the issue is. Has anyone ever had this issue before? And if so, what was the problem?
Here's my code, let me know if there's any other information needed:
protected override DataSet GetDefaultFilterTypes()
{
return DataSetUtility.ToDataSet(new List<Type> { typeof(Counterparty), typeof(Address), typeof(Contact),
typeof(Customer), typeof(Broker), typeof(ExchangeBroker), typeof(ExchangeBrokerAccount), typeof(Supplier), typeof(SupplierTerminalPriceMapping) });
}
public static DataSet ToDataSet(IList<Type> list)
{
DataSet ds = new DataSet();
foreach (Type item in list)
{
DataTable ta = new DataTable(item.ToString());
ds.Tables.Add(ta);
//add a column to table for each public property on T
foreach (var propInfo in item.GetProperties())
{
Type colType = Nullable.GetUnderlyingType(propInfo.PropertyType) ?? propInfo.PropertyType;
ta.Columns.Add(propInfo.Name, colType);
}
DataRow row = ta.NewRow();
foreach (var propInfo in item.GetProperties())
{
row[propInfo.Name] = DBNull.Value;
}
ta.Rows.Add(row);
}
return ds;
}
Here's the class definitions for ExchangeBroker and Supplier - the objects not getting columns:
public partial class Supplier : MomentumEntityBase
{
#region *** Properties
[DataMember(Order = 1, IsRequired = true)]
[Key,Required]
[GreaterThanZero]
public int SupplierId
{
get { return _supplierId; }
set
{
if (Equals(value, _supplierId)) return;
_supplierId = value;
NotifyPropertyChanged("SupplierId");
}
}
private int _supplierId;
[DataMember(Order = 2, IsRequired = true)]
[Required(AllowEmptyStrings = false),StringLength(64)]
public string CreationName
{
get { return _creationName; }
set
{
if (Equals(value, _creationName)) return;
_creationName = value;
NotifyPropertyChanged("CreationName");
}
}
private string _creationName;
[DataMember(Order = 3, IsRequired = true)]
[Required]
public DateTime CreationDate
{
get { return _creationDate; }
set
{
if (Equals(value, _creationDate)) return;
_creationDate = value;
NotifyPropertyChanged("CreationDate");
}
}
private DateTime _creationDate;
[DataMember(Order = 4, IsRequired = false)]
[StringLength(64)]
public string RevisionName
{
get { return _revisionName; }
set
{
if (Equals(value, _revisionName)) return;
_revisionName = value;
NotifyPropertyChanged("RevisionName");
}
}
private string _revisionName;
[DataMember(Order = 5, IsRequired = false)]
public DateTime? RevisionDate
{
get { return _revisionDate; }
set
{
if (Equals(value, _revisionDate)) return;
_revisionDate = value;
NotifyPropertyChanged("RevisionDate");
}
}
private DateTime? _revisionDate;
#endregion
#region *** Reverse Navigation
#endregion
#region *** Foreign Keys
// Foreign keys
public Counterparty Counterparty
{
get { return _counterparty; }
set
{
if (Equals(value, _counterparty)) return;
_counterparty = value;
CounterpartyChangeTracker = _counterparty == null ? null : new ChangeTrackingCollection<Counterparty> { _counterparty };
NotifyPropertyChanged("Counterparty");
}
}
private Counterparty _counterparty;
private ChangeTrackingCollection<Counterparty> CounterpartyChangeTracker { get; set; }
#endregion
#region *** CTOR / Initialize
public Supplier()
{
InitializePartial();
}
partial void InitializePartial();
#endregion
#region *** Error
public override string Error
{
get
{
var error = new StringBuilder();
if (TrackingState != TrackableEntities.TrackingState.Deleted)
{
if (!string.IsNullOrEmpty(base.Error))
{
error.AppendLine(base.Error);
}
}
return error.ToString();
}
}
#endregion
}
[DataContract]
public enum ExchangeBrokerColumns
{
[EnumMember]
ExchangeBrokerId = 0,
[EnumMember]
CreationName = 1,
[EnumMember]
CreationDate = 2,
[EnumMember]
RevisionName = 3,
[EnumMember]
RevisionDate = 4
}
// ExchangeBroker
//[DataContract]
[GeneratedCodeAttribute("EF.Reverse.POCO.Generator", "2.17.1.0")]
public partial class ExchangeBroker : MomentumEntityBase
{
#region *** Properties
[DataMember(Order = 1, IsRequired = true)]
[Key,Required]
[GreaterThanZero]
public int ExchangeBrokerId
{
get { return _exchangeBrokerId; }
set
{
if (Equals(value, _exchangeBrokerId)) return;
_exchangeBrokerId = value;
NotifyPropertyChanged("ExchangeBrokerId");
}
}
private int _exchangeBrokerId;
[DataMember(Order = 2, IsRequired = true)]
[Required(AllowEmptyStrings = false),StringLength(64)]
public string CreationName
{
get { return _creationName; }
set
{
if (Equals(value, _creationName)) return;
_creationName = value;
NotifyPropertyChanged("CreationName");
}
}
private string _creationName;
[DataMember(Order = 3, IsRequired = true)]
[Required]
public DateTime CreationDate
{
get { return _creationDate; }
set
{
if (Equals(value, _creationDate)) return;
_creationDate = value;
NotifyPropertyChanged("CreationDate");
}
}
private DateTime _creationDate;
[DataMember(Order = 4, IsRequired = false)]
[StringLength(64)]
public string RevisionName
{
get { return _revisionName; }
set
{
if (Equals(value, _revisionName)) return;
_revisionName = value;
NotifyPropertyChanged("RevisionName");
}
}
private string _revisionName;
[DataMember(Order = 5, IsRequired = false)]
public DateTime? RevisionDate
{
get { return _revisionDate; }
set
{
if (Equals(value, _revisionDate)) return;
_revisionDate = value;
NotifyPropertyChanged("RevisionDate");
}
}
private DateTime? _revisionDate;
#endregion
#region *** Reverse Navigation
// Reverse navigation
public ChangeTrackingCollection<ExchangeBrokerAccount> ExchangeBrokerAccounts
{
get { return _exchangeBrokerAccounts; }
set
{
if (Equals(value, _exchangeBrokerAccounts)) return;
_exchangeBrokerAccounts = value;
//NotifyPropertyChanged("ExchangeBrokerAccounts");
}
}
private ChangeTrackingCollection<ExchangeBrokerAccount> _exchangeBrokerAccounts;
#endregion
#region *** Foreign Keys
// Foreign keys
public Counterparty Counterparty
{
get { return _counterparty; }
set
{
if (Equals(value, _counterparty)) return;
_counterparty = value;
CounterpartyChangeTracker = _counterparty == null ? null : new ChangeTrackingCollection<Counterparty> { _counterparty };
NotifyPropertyChanged("Counterparty");
}
}
private Counterparty _counterparty;
private ChangeTrackingCollection<Counterparty> CounterpartyChangeTracker { get; set; }
#endregion
#region *** CTOR / Initialize
public ExchangeBroker()
{
ExchangeBrokerAccounts = new ChangeTrackingCollection<ExchangeBrokerAccount>();
InitializePartial();
}
partial void InitializePartial();
#endregion
#region *** Error
public override string Error
{
get
{
var error = new StringBuilder();
if (TrackingState != TrackableEntities.TrackingState.Deleted)
{
if (!string.IsNullOrEmpty(base.Error))
{
error.AppendLine(base.Error);
}
if (ExchangeBrokerAccounts.HasError())
{
error.AppendLine("ExchangeBrokerAccounts contains validation error(s).");
}
}
return error.ToString();
}
}
#endregion
}
I have this functional query where I only used fictive tables names for security concerns :
SELECT
h.CENID,
h.BMHFMC,
h.BMHDONEMIDASSTEP1,
h.BMHDONEMIDASSTEP2,
h.LMIID,
h.BMHHOLD,
h.BMHBATCHMIDAS,
h.BMHFMCVALUEDATE AS HeaderValueDate,
h.SUNID,
h.BRAID,
d.BMHID,
d.BMDRUBRIQUE,
d.BMDCLIENT,
d.BMDSEQUENCE,
d.BMDDATE,
d.BMDDEVISE,
d.BMDMONTANT,
d.BMDTYPE,
d.BMDNOTE,
d.BMDENTRYNBRE,
v.DEVDECIMAL ,
NVL(t.TYPVERIFCOMPTEMIDAS, 0) AS TYPVERIFCOMPTEMIDAS
FROM dbo.TableOne h
INNER JOIN dbo.Tabletwoo d
ON h.BMHID = d.BMHID
INNER JOIN dbo.tableThree v
ON d.BMDDEVISE = v.DEVID
LEFT JOIN dbo.TableFour t
ON t.TYPID=h.BMHFMC
WHERE d.BMDMONTANT != 0
AND h.BMHDONEMIDASSTEP1 = 0
AND h.BMHDONEMIDASSTEP2 = 0
AND h.LMIID = 0
AND h.BMHHOLD = 0
And I made a class in order to bind every fields
public class Batch :BaseRepository ,IList<Batch>
{
public Batch()
{
}
private string cendid;
private string bmhfmc;
private double bmhdonemidasstep1;
private double bmhdonemidasstep2;
private double lmiid;
private double bmhhold;
private double bmhbatchmidas;
private DateTime headervaluedateordinal;
private double sunid; //
private string bradid; //
private double bmhid;
private string bmdrubirique; //
private string bmdclient;
private string bmdsequence;
private DateTime bmddate;
private string bmddevise;
private double bmdmontant;
private string bmdtype;
private string bmdnote;
private string bmdentrynbre; //
private double devdecimalordinal;
private double typverifcomptemidasordinal;
public Batch(string cendid, string bmhfmc, double bmhdonemidasstep1, double bmhdonemidasstep2, double lmiid, double bmhhold, double bmhbatchmidas, DateTime headervaluedateordinal, double sunid, string bradid, double bmhid, string bmdrubirique, string bmdclient, string bmdsequence, DateTime bmddate, string bmddevise, double bmdmontant, string bmdtype, string bmdnote, string bmdentrynbre, double devdecimalordinal, double typverifcomptemidasordinal)
{
this.cendid = cendid;
this.bmhfmc = bmhfmc;
this.bmhdonemidasstep1 = bmhdonemidasstep1;
this.bmhdonemidasstep2 = bmhdonemidasstep2;
this.lmiid = lmiid;
this.bmhhold = bmhhold;
this.bmhbatchmidas = bmhbatchmidas;
this.headervaluedateordinal = headervaluedateordinal;
this.sunid = sunid;
this.bradid = bradid;
this.bmhid = bmhid;
this.bmdrubirique = bmdrubirique;
this.bmdclient = bmdclient;
this.bmdsequence = bmdsequence;
this.bmddate = bmddate;
this.bmddevise = bmddevise;
this.bmdmontant = bmdmontant;
this.bmdtype = bmdtype;
this.bmdnote = bmdnote;
this.bmdentrynbre = bmdentrynbre;
this.devdecimalordinal = devdecimalordinal;
this.typverifcomptemidasordinal = typverifcomptemidasordinal;
}
public string Cendid
{
get { return cendid; }
set { cendid = value; }
}
public string Bmhfmc
{
get { return bmhfmc; }
set { bmhfmc = value; }
}
public double Bmhdonemidasstep1
{
get { return bmhdonemidasstep1; }
set { bmhdonemidasstep1 = value; }
}
public double Bmhdonemidasstep2
{
get { return bmhdonemidasstep2; }
set { bmhdonemidasstep2 = value; }
}
public double Lmiid
{
get { return lmiid; }
set { lmiid = value; }
}
public double Bmhhold
{
get { return bmhhold; }
set { bmhhold = value; }
}
public double Bmhbatchmidas
{
get { return bmhbatchmidas; }
set { bmhbatchmidas = value; }
}
public DateTime Headervaluedateordinal
{
get { return headervaluedateordinal; }
set { headervaluedateordinal = value; }
}
public double Sunid
{
get { return sunid; }
set { sunid = value; }
}
public string Bradid
{
get { return bradid; }
set { bradid = value; }
}
public double Bmhid
{
get { return bmhid; }
set { bmhid = value; }
}
public string Bmdrubirique
{
get { return bmdrubirique; }
set { bmdrubirique = value; }
}
public string Bmdclient
{
get { return bmdclient; }
set { bmdclient = value; }
}
public string Bmdsequence
{
get { return bmdsequence; }
set { bmdsequence = value; }
}
public DateTime Bmddate
{
get { return bmddate; }
set { bmddate = value; }
}
public string Bmddevise
{
get { return bmddevise; }
set { bmddevise = value; }
}
public double Bmdmontant
{
get { return bmdmontant; }
set { bmdmontant = value; }
}
public string Bmdtype
{
get { return bmdtype; }
set { bmdtype = value; }
}
public string Bmdnote
{
get { return bmdnote; }
set { bmdnote = value; }
}
public string Bmdentrynbre
{
get { return bmdentrynbre; }
set { bmdentrynbre = value; }
}
public double Devdecimalordinal
{
get { return devdecimalordinal; }
set { devdecimalordinal = value; }
}
public double Typverifcomptemidasordinal
{
get { return typverifcomptemidasordinal; }
set { typverifcomptemidasordinal = value; }
}
Now when I execute the query into a list using dapper
Connection conn = new Connection();
OracleConnection connection = conn.GetDBConnection();
myList= connection.Query<Batch>(querySql).ToList();
Now,while debugging, all fields returns the expected values .But, I noticed those fields below are null in myList not empty but really null , but the problem is they aren't null in the database
Bmdrubirique , Sunid, Bmdentrynbre, Bradid ,Cenid
In oracle database those fields are like the following :
CENID is VARCHAR2(3 BYTE)`
Bmhid is VARCHAR2(3 BYTE)
Sunid is NUMBER(38,0)
Bradid is VARCHAR2(3 BYTE)
I don't get it , where did it go wrong? why other fields are properly loaded while those returns null value ?
My default assumption would be that there is a typo in the real code and the constructor is assigning a value from a field to itself. However, frankly: since you have a public Batch() {} constructor, I'm not sure what the benefit of the second one is - it just adds risk of errors. Likewise with the fields and manual properties.
So if this as me, where you currently have (simplified to two properties):
public class Batch
{
private string cendid;
private string bmhfmc;
public Batch() {}
public Batch(string cendid, string bmhfmc)
{
this.cendid = cendid;
this.bmhfmc = bmhfmc;
}
public string Cendid
{
get { return cendid; }
set { cendid = value; }
}
public string Bmhfmc
{
get { return bmhfmc; }
set { bmhfmc = value; }
}
}
I would have literally just:
public class Batch
{
public string Cendid {get;set;}
public string Bmhfmc {get;set;}
}
All of the rest of the code is just opportunities to make coding errors.
Now: the reason that Cendid is null is because: the column is CENID - only one d. This means that dapper isn't even using your custom constructor, because it isn't a perfect match between the constructor and the columns. Ditto the other fields like BRAID vs BRADID.
So the next thing to do is to fix the typos.
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
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
I have converted the following two classes to c# from vb.net, but get a reference error. Can someone please help or explain why it does not work in c# but does in vb.net?
Member class:
public class Member
{
#region "Fields"
private string fPiecemark;
private string fMemberType;
private string fSize;
private string fTotalWeight;
private int fSheetKey;
private string fDescription;
private string fStructType;
#endregion
private string fMemberSheetIndex;
#region "Constructors"
//Default class Constructor
public Member()
{
fPiecemark = string.Empty;
fMemberType = string.Empty;
fSize = string.Empty;
fTotalWeight = string.Empty;
fSheetKey = 0;
fStructType = string.Empty;
}
public Member(string Piecemark, string MemberType, string Description, string Size, string TotalWeight, string StructType, string MemberSheetIndex, int SheetID)
{
this.Piecemark = Piecemark;
this.MemberType = MemberType;
this.Description = Description;
this.Size = Size;
this.TotalWeight = TotalWeight;
this.StructType = StructType;
this.MemberSheetIndex = MemberSheetIndex;
this.SheetKey = SheetID;
if (!MbrSheet.mSheet.ContainsKey(SheetID))
{
MbrSheet.mSheet.Add(SheetID, new MbrSheet(SheetID));
}
MbrSheet.mSheets[SheetID].Members.Add(this);
}
#endregion
#region "Properties"
public string Piecemark
{
get { return fPiecemark; }
set { fPiecemark = value; }
}
public string MemberType
{
get { return fMemberType; }
set { fMemberType = value; }
}
public string TotalWeight
{
get { return fTotalWeight; }
set { fTotalWeight = value; }
}
public string Size
{
get { return fSize; }
set { fSize = value; }
}
public int SheetKey
{
get { return fSheetKey; }
set { fSheetKey = value; }
}
public string Description
{
get { return fDescription; }
set { fDescription = value; }
}
public string StructType
{
get { return fStructType; }
set { fStructType = value; }
}
public string MemberSheetIndex
{
get { return fMemberSheetIndex; }
set { fMemberSheetIndex = value; }
}
#endregion
}
MbrSheet class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Globalization;
public class MbrSheet
{
public static Dictionary<int, MbrSheet> mSheets = new Dictionary<int, MbrSheet>();
public int mSheet { get; set; }
public List<Member> Members { get; set; }
public MbrSheet(int MbrSheet)
{
Members = new List<Member>();
this.mSheet = MbrSheet;
}
public static decimal WeightByType(string MemberType)
{
var subset = mSheets.Where(kvp => kvp.Value.Members.Where(m => m.MemberType == MemberType).Count() > 0);
decimal wbt = 0;
wbt += mSheets
.Where(kvp => kvp.Value.Members.Where(m => m.MemberType == MemberType).Count() > 0)
.Sum(kvp => kvp.Value.Members.Sum(m => Convert.ToDecimal(m.TotalWeight, CultureInfo.InvariantCulture)));
return wbt;
}
}
I get error but don't know why
An object reference is required for the non-static field, method, or property for MbrSheet.mSheet, but both worked in VB.net
if (!MbrSheet.mSheet.ContainsKey(SheetID)) // Error on !MbrSheet.mSheet
{
MbrSheet.mSheet.Add(SheetID, new MbrSheet(SheetID)); // Error on MbrSheet.mSheet
}
I think you should use this:
if (!MbrSheet.mSheets.ContainsKey(SheetID))
{
MbrSheet.mSheets.Add(SheetID, new MbrSheet(SheetID));
}
Pay attention to mSheets you are using mSheet.
You can also use tools to convert codes:
http://www.developerfusion.com/tools/convert/csharp-to-vb/
http://codeconverter.sharpdevelop.net/SnippetConverter.aspx