已经在项目上工作了一段时间,基本上它是C#和Mysql的组合作为服务器端系统。由于性能问题,我将代码ADO.NET交给我的mysql查询,但我遇到了一个问题,因为我想减少需要编写的代码量。
让我们说
ItemService类有方法(以下代码只是示例)
protected internal List<Item> Read()
{
List<Item> itemList = new List<Item>();
String query = @"SELECT * FROM items";
itemList = IRead(query);
return itemList;
}
protected internal Item Read(int id)
{
List<Item> itemList = new List<Item>();
Item item = new Item();
String query = String.Format(@"SELECT * FROM items WHERE id = {0}", id);
itemList = IRead(query);
item = itemList.FirstOrDefault();
return item;
}
protected internal List<Item> Read(int startId, int limit, String orderBy = "id", String order = "ASC")
{
List<Item> itemList = new List<Item>();
String query = String.Format(@"SELECT * FROM items WHERE id >= {0} ORDER BY '{1}' '{2}' LIMIT {3}", startId, orderBy, order, limit);
itemList = IRead(query);
return itemList;
}
OrderService类具有非常相似的方法
protected internal List<Order> Read()
{
List<Order> orderList = new List<Order>();
String query = @"SELECT * FROM items";
orderList = IRead(query);
return orderList;
}
protected internal Order Read(int id)
{
Order order = new Order();
String query = String.Format(@"SELECT * FROM invoices WHERE id = {0}", id);
order = IRead(query).FirstOrDefault();
return order;
}
我正在考虑使用抽象类,但是我如何处理不同的返回对象(动态除外)以及方法内的不同字符串查询。非常感谢你的帮助。
答案 0 :(得分:1)
您可以创建一个抽象基类,为您完成大部分繁重工作:
public abstract class ItemBase<T> where T : new()
{
public abstract string table_name { get; }
protected internal T Read(int id)
{
var query = $@"SELECT * FROM {table_name} WHERE id = {id}";
//var itemList = IRead(query);
Console.WriteLine(query); //Did this as console output for testing
return new T(); // temList.FirstOrDefault();
}
protected internal List<T> Read(int startId, int limit, string orderBy = "id", string order = "ASC")
{
string query = $@"SELECT * FROM {table_name} WHERE id >= {startId} ORDER BY {orderBy} {order} LIMIT {limit}";
Console.WriteLine(query); //Console output for testing
return null;
//return IRead(query);
}
}
然后你可以像这样创建各个记录类:
public class Item : ItemBase<Item>
{
public override string table_name => "items";
}
您可以像这样使用它:
//Console Application:
class Program
{
static void Main(string[] args)
{
var i = new Item();
i.Read(12);
i.Read(1, 2);
Console.ReadLine();
}
}