6.2Классы документов Прежде чем приводить исходные коды классов документов нужно сказать несколько слов о служебном классе Link. Так как для системы важна информация о идентификаторе объекта, на которого сослаться, а также название таблицы базы данных, а для пользователя наиболее важно представление, было принято решение сконцентрировать все эти три вещи в одной сущности. Метод ToString()необходим для нормального отображения экземпляра в контролах, с которыми осуществляется связь полей объектов типа Link. Кроме того для возможности упорядочивания необходима реализация интерфейса IComparable, а именно метода CompareTo(object obj).
public class Link : IComparable
{
public string TableName { get; private set; }
public int Id { get; set; }
public string Name { get; set; } public Link(string tableName)
{
this.TableName = tableName;
} public Link(string tableName, int id, string name)
{
this.TableName = tableName;
this.Id = id;
this.Name = name;
} public Link(string tableName, int id)
{
this.TableName = tableName;
this.Id = id;
this.Name = MySQL.GetCommand("SELECT `Name` FROM `"+tableName+
"` WHERE `id` = '" + id + "'").ExecuteScalar().ToString();
} public Link(string tableName, DataRow row, string colPrefix)
{
this.TableName = tableName;
this.Id = int.Parse(row.GetCol(colPrefix+"_id"));
this.Name = row.GetCol(colPrefix + "_name");
} public override string ToString()
{
return this.Name;
} public int CompareTo(object obj)
{
var other = obj as Link;
int result = this.Name.CompareTo(other.Name);
return result == 0 ? this.Id.CompareTo(other.Id) : result;
}
}
| Далее приведены исходные коды класса Operation и унаследованного от него класса OrderIn. Кроме того показан класс OrderInParameter. Класс заявки имеет в качестве одного из свойств типизированный список параметров.
public class Operation : IComparable
{
public DateTime Date { get; set; }
public int Id { get; set; } public Operation()
{
this.Date = DateTime.Now;
} public int CompareTo(object obj)
{// Функция нужна для возможности упорядочивания
var other = obj as Operation;
int result = this.Date.CompareTo(other.Date);
return result == 0 ? this.Id.CompareTo(other.Id) : result;
} public virtual bool Save()
{
return true;
}
}
|
public class OrderIn : Operation
{
public Link Client { get; set; }
public float Count { get; set; }
public int Status { get; set; } // Пока число, потом надо будет создать перечисление
public List<OrderInParameter> Parameters { get; set; } private Link _good;
public Link Good
{
get { return _good; }
set {
_good = value;
GenerateNewParameters();
}
}
public OrderIn()
{
this.Client = MySQL.CurrentUser;
} public OrderIn(int id)
{
var dt = new DataTable(); string SQLstring =
@"SELECT orderin.id as id,
orderin.date as date,
orderin.client as client_id,
users.Name as client_name,
orderin.good as good_id,
kgoods.Name as good_name,
orderin.count as count,
orderin.status as status
FROM orderin
LEFT JOIN users ON orderin.client = users.id
LEFT JOIN kgoods ON orderin.good = kgoods.id
WHERE orderin.id = '" + id + "'"; dt.Fill(SQLstring); if (dt.Rows.Count > 0)
{
var row = dt.Rows[0];
this.Id = id;
this.Date = DateTime.Parse(row.GetCol("date"));
this.Client = new Link("users", row, "client");
// присваиваю приватному свойству для того, чтобы
// геттер не генерил новые параметры
_good = new Link("kgoods", row, "good");
this.Count = float.Parse(row.GetCol("count"));
this.Status = int.Parse(row.GetCol("status"));
}
dt.Clear(); SQLstring =
@"SElECT o.id as id,
o.checked as checked,
o.characteristic as char_id,
k.name as char_name,
o.equality as equality,
o.val as val
FROM orderinparameters as o
LEFT JOIN kcharacteristics as k ON o.characteristic = k.id
WHERE o.idorder = '" + this.Id + "'"; dt.Fill(SQLstring); var parameters = dt.AsEnumerable()
.Select(row => new OrderInParameter(this,
row.GetId(),
row.GetBoolCol("checked"),
new Link("kcharacteristics", row, "char"),
row.GetCol("equality"),
row.GetCol("val"))); this.Parameters = new List<OrderInParameter>(parameters);
} public void GenerateNewParameters()
{
var dt = new DataTable(); string SQLstring =
@"SELECT curCh.id as id,
curCh.checked as checked,
kc.id as char_id,
kc.Name as char_name,
curCh.equality as equality,
curCh.val as val
FROM kchargoods as kcg
LEFT JOIN kcharacteristics as kc ON kcg.KindOfCharacteristic = kc.id
LEFT JOIN (
SELECT id, checked, characteristic, val, equality
FROM orderinparameters
WHERE idorder = '" + this.Id+@"'
) as curCh ON kc.id = curCh.characteristic
WHERE KindOfGood = '" + this.Good.Id + "'"; dt.Fill(SQLstring); var parameters = dt.AsEnumerable()
.Select(row => new OrderInParameter(this,
row.GetId(),
row.GetBoolCol("checked"),
new Link("kcharacteristics", row, "char"),
row.GetCol("equality"),
row.GetCol("val"))); this.Parameters = new List<OrderInParameter>(parameters);
} public void OpenForm(Form1 mainForm)
{
frmOrderIn f;
if (mainForm.OpenWindows.Contains(this.ToString()))
{
f = (frmOrderIn)mainForm.OpenWindows[this.ToString()];
f.Activate();
}
else
{
f = new frmOrderIn(this, mainForm);
mainForm.OpenWindows.Add(this.ToString(), f);
f.Show();
}
} public override string ToString()
{
return "Заявка клиента № "+this.Id.ToString() + " от " + this.Date.ToString();
} public override bool Save()
{
var command = MySQL.GetCommand(
(this.Id == 0 ? "INSERT INTO" : "UPDATE") + " orderin SET " +
"`date` = " + this.Date.ToMySQL() + ", " +
"`client` = " + this.Client.Id + ", " +
"`status` = " + this.Status + ", " +
"`good` = " + this.Good.Id + ", " +
"`count` = " + this.Count + " " +
(this.Id == 0 ? "" : ("WHERE id = " + this.Id + "")));
command.ExecuteNonQuery();
this.Id = this.Id == 0 ? MySQL.GetLastId() : this.Id; // Сначала удалить те характеристики, которые были со старым товаром,
// а потом установить характеристики, которые должны описывать новый товар
command.CommandText = "DELETE from orderinparameters WHERE idorder = '" + this.Id + "'";
command.ExecuteNonQuery();
if (this.Parameters.Count != 0)
{
var SQLvalues =
(from par in Parameters
select ("(" +
par.Id + ", " + // id
par.Order.Id + ", " + // idorder
(par.Checked ? "1" : "0") + ", " + // checked
par.Characteristic.Id + ", " + // characteristic
"'" + par.Equality + "', " + // equality
"'" + par.Val + "')" // val
)).Aggregate((a, b) => a + ", " + b);
command.CommandText =
@"INSERT INTO orderinparameters (id, idorder, checked, characteristic, equality, val)
VALUES " + SQLvalues + ";";
command.ExecuteNonQuery();
}
return true;
}
} public class OrderInParameter : IComparable
{
public int Id { get; set; }
public OrderIn Order { get; set; }
public bool Checked { get; set; }
public Link Characteristic { get; set; }
public object Val { get; set; } private string _equality;
public string Equality
{
get { return _equality; }
set { _equality = value == "" ? "=" : value; }
} public OrderInParameter()
{
this.Checked = false;
this.Equality = "=";
} public OrderInParameter(OrderIn order)
{
this.Order = order;
this.Checked = false;
this.Equality = "=";
} public OrderInParameter(OrderIn order, int id)
{
var dt = new DataTable();
string SQlstring =
@"SElECT o.id as id,
o.idorder as idorder,
o.checked as checked,
k.id as char_id,
k.name as char_name,
o.equality as equality,
o.val as val
FROM orderinparameters as o
LEFT JOIN kcharacteristics as k ON o.characteristic = k.id
WHERE o.id = '" + id + "'";
dt.Fill(SQlstring); if (dt.Rows.Count > 0)
{
var row = dt.Rows[0]; this.Id = id;
this.Order = order;
this.Checked = row.GetBoolCol("checked");
this.Characteristic = new Link("kcharacteristics", row, "char");
this.Equality = row.GetCol("equality");
this.Val = row.GetCol("val");
}
} public OrderInParameter(OrderIn order, int id, bool check, Link characteristic, string equality, object val)
{
this.Id = id;
this.Order = order;
this.Checked = check;
this.Characteristic = characteristic;
this.Equality = equality;
this.Val = val;
} public int CompareTo(object obj)
{
var other = obj as OrderInParameter;
int result = this.Characteristic.CompareTo(other.Characteristic);
return result;
}
}
|
|