我想使用存储库模式创建一个窗口应用程序...以下是我的存储库代码。
模型是:
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();
}
}
}
答案 0 :(得分:0)
最好的方法是使用Generic存储库,它允许您在调用方法时启动对象。
public static void Save<T>(T model) where T : class
{
// your Context code for saving
}
// call your method
Pet pet = new Pet();
Save<Pet>(pet)
答案 1 :(得分:0)
您可以使用实施&#34; EFPetRepository&#34;通过添加相关的命名空间/引用,在任何其他项目中接口IPetRepository。它应该如下
private void btnadd_Click(object sender, EventArgs e)
{
var pet = (Models.Pet)sender;
pet.petName= "pet1";
pet.petCode = "p124";
repo.SavePet(pet);
}
private void btndelete_Click(object sender, EventArgs e)
{
var pet = (Models.Pet)sender;
repo.delete(pet.ID);
}