如何从main方法调用业务对象类



我已经将代码分离为业务对象、访问层,如下所示:

void Main()
{

}
//====================================================================
// Business object
public class ExpenseBO
{
public void MakeExpense(ExpensePayload payload)
{
var trA = new TrAccess();
var acA = new AcAccess();
var account = acA.MakeAccount(payload.Account);
payload.Transaction.Account = account;
trA.MakeTransaction(payload.Transaction);
}
}
//----------------------------------------------------------------------------
public class TrAccess
{
private const string connString = "Host=localhost;Username=postgres;Password=1234;Database=ExpenseManagerDB";
public void MakeTransaction(T t) 
{
using (var connection = new NpgsqlConnection(connString))
{
connection.Execute(@"INSERT INTO transaction (account_id, amount, date, note)
SELECT a.account_id,@amount, @date, @note
FROM account AS a
WHERE a.account_name = @account_name", new { t.Amount, t.Date, t.Note, a.Account_Name });
}
}
}
public class AcAccess
{
private const string connString = "Host=localhost;Username=postgres;Password=1234;Database=ExpenseManagerDB";
public void MakeAccount(A a)
{
using (var connection = new NpgsqlConnection(connString))
{
connection.Execute(@"INSERT INTO account(account_name, type)
VALUES(@account_name, @type)", new { account.Account_Name, account.Type });
}
}
}
public class T
{
public int Transaction_Id { get; set; }
public int Account_Id { get; set; }
public decimal Amount { get; set; }
public string Note { get; set; }
public DateTime Date { get; set; }
}
public class A
{
public int Account_Id { get; set; }
public string Account_Name { get; set; }
public string Type { get; set; }
}
//--------------------------------------------
public class ExpensePayload
{
public T Transaction { get; set; }
public A Account { get; set; }
}

现在,我想从将创建两个对象的主要方法中调用ExpenseBO类方法MakeExpense,并用它们调用TrAccessAcAccess

但是有一个ExpensePayload类。如果我想在main方法中调用ExpenseBOMakeExpense方法,我应该怎么做?我应该如何创建ExpensePayload类对象并在main方法中调用它?

public void AccessToExpenseBO()
{
var request = new ExpensePayload
{
Account = new A
{
Account_Id = 1,
Account_Name = "Account 1",
Type = "Type 1"
},
Transaction = new T
{
Account_Id = 1,
Amount = 25,
Date = DateTime.Now,
Note = "Note 1",
Transaction_Id = 25
}
};
var expenseBO = new ExpenseBO();
expenseBO.MakeExpense(request);
}

基本上,你可以访问我如何显示它,但是,我会在你的代码基础上添加一些评论。

MakeAccount方法不返回值,因此无法将其分配给变量。在这种情况下,您应该返回一个值,即Account,以便在MakeExpense方法中执行您想要的操作。

public void MakeExpense(ExpensePayload payload)
{
var trA = new TrAccess();
var acA = new AcAccess();
var account = acA.MakeAccount(payload.Account); //void method
payload.Account = account; // so, there is no an account
trA.MakeTransaction(payload.Transaction);
}
var payl = new ExpensePayload {
Transaction = // some T,
Account = // Some A
}
var bo = new ExpenseBo();

bo.MakeExpense(payl);

相关内容

  • 没有找到相关文章

最新更新