私は効果的な追加、更新、削除などのためのリポジトリの種類を書き込もうとしています。しかし、私は2つのクラス(ErpEntitiesとDataRepository)を処分する方法がもっと助言されています。私は戻り値の後に処分したい。 Shorthlyとeffectivelly :( 敬具...EF 3.5 -4.0に有効なDispose()を持つリポジトリを書くにはどうすればいいですか?
namespace WinApp.EF
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnSave_Click(object sender, EventArgs e)
{
using (ErpEntities erp = new ErpEntities())
{
erp.SaveCustomer(textBox1.Text, textBox2.Text);
}
}
}
public class ErpEntities : IDisposable
{
public int SaveCustomer(string Name, string SurName)
{
using (DataRepository<Customer> repository = new DataRepository<Customer>(new TestErpEntities()))
{
return repository.Add(new Customer() { Name = Name, SurName = SurName });
}
}
public void Dispose()
{
GC.SuppressFinalize(this);
}
}
public interface IRepository<T> : IDisposable where T : class
{
int Add(T entity);
}
public class DataRepository<T> : IRepository<T> where T : class
{
private TestErpEntities _context;
public DataRepository()
{
}
public DataRepository(TestErpEntities context)
{
_context = context;
}
public int Add(T entity)
{
_context.AddObject(typeof(T).Name, entity);
int saveValue = _context.SaveChanges();
return saveValue;
}
public void Dispose()
{
if (_context != null)
_context.Dispose();
}
}
}
この記事をご覧ください。それは助けるかもしれません:http://bit.ly/bF7jL3。 – Steven
なぜ人生は困難になるのですか? DIコンテナを使用し、コンテキストを破棄します。 – RPM1984
DIコンテナとは何ですか? – Penguen