我认为您回答了自己的问题,这取决于您使用的表示层。但是,当您想保持此业务层通用时,您将不得不使用 ID。
这是另一个想法。我个人喜欢将所有突变包装到类中,我称之为命令。例如,您可以有一个CreateUserCommand
从基本命令继承的。这将允许您像这样使用它(我在这里假设 C#):
var command = new CreateUserCommand();
command.UserCompanyId = companyId;
command.UserName = name;
command.Execute();
将此逻辑包装在命令中是非常好的模式。它允许您将单个用例放在单个命令中。尤其是当命令中的逻辑量增加时,您会喜欢这种模式,但我发现它对 CRUD 操作也非常有效。
此模式还允许您在基类中抽象事务模型。基类可以包装调用以在数据库事务中执行。这是一个简单的实现:
public abstract class CommandBase
{
public void Execute()
{
this.Validate();
using (var conn = ContextFactory.CreateConnection())
{
conn.Open();
using (var transaction = conn.BeginTransaction())
{
using (var db = ContextFactory.CreateContext(conn))
{
this.ExecuteInternal(db);
db.SubmitChanges();
}
transaction.Commit();
}
}
}
protected virtual void Validate() { }
protected abstract void ExecuteInternal(YourDataContext context);
}
这就是它的CreateUserCommand
样子:
public class CreateUserCommand : CommandBase
{
public int UserCompanyId { get; set; }
public string UserName { get; set; }
protected override void ExecuteInternal(YourDataContext context)
{
this.InsertNewUserInDatabase(context);
this.ReportCreationOfNewUser();
}
protected override void Validate()
{
if (this.UserCompanyId <= 0)
throw new InvalidOperationException("Invalid CompanyId");
if (string.IsNullOrEmpty(this.UserName))
throw new InvalidOperationException("Invalid UserName");
}
private void InsertNewUserInDatabase(YourDataContext context)
{
db.Users.InsertOnSubmit(new User()
{
Name = this.UserName,
CompanyId = this.CompanyId
});
}
private void ReportCreationOfNewUser()
{
var message = new MailMessage();
message.To = Configuration.AdministratorMailAddress;
message.Body = "User " + this.Name + " was created.";
new SmtpClient().Send(message);
}
}
我希望这有帮助。