私はリポジトリパターンを使用してウィンドウアプリケーションを作成したいと思います...私のリポジトリコードは次のとおりです。リポジトリからのコードの保存と削除
モデルは次のとおりです。モデルの
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; }
}
}
インタフェース:インタフェース
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;
}
}
}
ため
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 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();
}
}
}