0
我想使用存储库模式创建窗口应用程序...以下是我的存储库代码。如何重用从存储库中保存和删除代码
模式是:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
namespace Domain.Models
{
public class Pet
{
public int ID { get; set; }
[Display(Name="Pet Name")]
public String PetName { get; set; }
public String Detail { get; set; }
[DataType(DataType.Currency)]
public Double Price { get; set; }
[Display(Name="Pet Code")]
public int PetCode { get; set; }
}
}
接口模式:
using Domain.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Domain.Abstract
{
public interface IPetRepository
{
IEnumerable<Pet> Pets { get; }
bool SAvePet(Pet pet);
Pet DeletePet(int ID);
}
}
实施接口
namespace Domain.Concret
{
public class EFPetRepository:IPetRepository
{
public readonly DbAccess context = new DbAccess();
public IEnumerable<Models.Pet> Pets
{
get { return context.Pets ; }
}
public bool SAvePet(Models.Pet pet)
{
if (pet.ID == 0)
{
context.Pets.Add(pet);
}
else
{
var pt = context.Pets.Find(pet.ID);
if (pt.ID != null)
{
pt.PetCode = pt.PetCode;
pt.PetName = pt.PetName;
pt.Price = pt.Price;
pt.Detail = pt.Detail;
}
}
try
{
context.SaveChanges();
return true;
}
catch (Exception)
{
return false;
}
}
public Models.Pet DeletePet(int ID)
{
var pt = context.Pets.Find(ID);
if (pt != null)
{
context.Pets.Remove(pt);
context.SaveChanges();
}
return pt;
}
}
}
现在我想在窗口的形式使用它......凭什么我在这里重复使用它的代码来保存和删除按钮:
namespace inventryMangt
{
public partial class pet : Office2007Form
{
private readonly IPetRepository repo;
public pet()
{
repo = new EFPetRepository();
InitializeComponent();
}
private void btnadd_Click(object sender, EventArgs e)
{
repo.SavePet();
}
private void btndelete_Click(object sender, EventArgs e)
{
repo.delete();
}
}
}