throw new ArgumentException("customerId");
return _dataBase.Customers
.SingleOrDefault(x => x.customerId == customerId);
}
public IEnumerable GetCustomersByProduct(Guid productId) {
if (productId == Guid.Empty)
throw new ArgumentException("customerId");
return _dataBase.Orders
.Where(x => x.productId == productId)
.Select(x => x.Customer).Distinct();
}
}
public class OrderRepository : IOrderRepository {
private readonly MyDatabaseDataContext _dataBase;
public OrderRepository(MyDatabaseDataContext db)
{
if (db == null)
throw new ArgumentNullException("db");
_dataBase = db;
}
public IOrder GetOrderByld(Guid orderld)
{
if (orderId == Guid.Empty)
throw new ArgumentException("orderId");
return _dataBase.Orders
.SingleOrDefault(x => x.orderId == orderId);
}
public IEnumerable GetCustomerOrders(Guid customerId)
{
if (customerId == Guid.Empty)
throw new ArgumentException("customerId");
return _dataBase.Orders
.Where(x => x.customerId == customerId)
.Select(x => x);
}
}
public class ProductRepository : IProductRepository {
private readonly MyDatabaseDataContext _dataBase;
public ProductRepository(MyDatabaseDataContext db)
{
if (db == null)
throw new ArgumentNullException("db");
_dataBase = db;
}
public IProduct GetProductById(Guid productId)
{
if (productId == Guid.Empty)
throw new ArgumentException("productId");
return _dataBase.Products
.SingleOrDefault(x => x.productId == productId);
}
public IEnumerable GetAvailableProducts()
{
return _dataBase.Products.Where(x => x.isAvailable)
.Select(x => x);
}
public IEnumerable GetProductListByName(string name)
{
if (string.IsNullOrEmpty(name))
throw new ArgumentException("name");
return _dataBase.Products
.Where(x => x.name.Contains(name))
.Select(x => x);
}
}
Далее создадим сервисы, которые будут помогать нам манипулировать данными. Сначала определим интерфейсы сервисов:
public interface ICustomerService {
ICustomer Create(string name, string phone, string address);
void Delete(ICustomer customer);
void Update(ICustomer customer, string name,
string phone, string address);
}
public interface IOrderService {
IOrder Create(ICustomer customer, IProduct product, int count,
DateTime orderDateTime);
void Delete(IOrder order);
void Update(IOrder order, ICustomer customer,
IProduct product, int count, DateTime orderDateTime);
}
public interface IProductService {
IProduct Create(string name, bool isAvailable, decimal cost);
void Delete(IProduct product);
void Update(IProduct product, string name,
bool isAvailable, decimal cost);
Реализуем интерфейсы сервисов, как показано в листинге 3.4, для класса customerService. Чтобы уменьшить количество кода, приводить реализацию для других классов мы не будем, для остальных классов определяем методы Create, Deleteи Updateточно таким же образом.
Листинг 3.4. Реализация интерфейсов сервисов
public class CustomerService : ICustomerService {
private readonly MyDatabaseDataContext _database;
public CustomerService(MyDatabaseDataContext db)
{
if (db == null)
throw new ArgumentNullException("db");
_database = db;
}
public ICustomer Create(string name, string phone, string address)
{
if (String.IsNullOrEmpty(name))
throw new ArgumentNullException("name");
Customer customer = new Customer()
{
CustomerId = Guid.NewGuid(),
Address = address,
Phone = phone,
Name = name
};
_database.Customers.InsertOnSubmit(customer);
return customer;
}
public void Delete(ICustomer customer)
{
if (customer == null)
throw new ArgumentNullException("customer");
_database.Customers.DeleteOnSubmit((Customer)customer);
}
public void Update(ICustomer customer, string name,
string phone, string address)
{
if (customer == null)
throw new ArgumentNullException("customer");
if (String.IsNullOrEmpty(name))
throw new ArgumentNullException("name");
customer.Name = name;
customer.Phone = phone;
customer.Address = address;
}
}
Нетрудно заметить, что наш код зависит от определенного типа контекста данных. Следовательно, при использовании этого кода мы вынуждены будем передавать созданный контекст базы данных, а следовательно, будем привязаны к нему. Для того чтобы избавиться от этой зависимости, создадим новый элемент, который будет возвращать необходимый нам контекст базы данных.
public class UnitOfWork : IDisposable {
private readonly MyDatabaseDataContext _database;
public MyDatabaseDataContext DataContext {
get
{
return _database;
}
}
private bool _disposed;
public UnitOfWork()
{
_database = new MyDatabaseDataContext();
}
public void Commit()
{
_database.SubmitChanges();
}
public void Dispose()
{
Dispose(true); GC.SuppressFinalize(this);
}
Читать дальше
Конец ознакомительного отрывка
Купить книгу