Utilisez une aide DBContext de GenericType
public class ContextHelper<T> : IContextHelper<T>
{
//Instantiate your own EntityFrameWork DB context here,
//Ive called the my EntityFramework Namespace 'EF' and the context is named 'Reporting'
private EF.DataContext DbContext = new EF.DataContext();
public bool Insert<T>(T row) where T : class
{
try
{
DbContext.Set<T>().Add(row);
DbContext.SaveChanges();
return true;
}
catch(Exception ex)
{
return false;
}
}
public bool Update<T>(T row) where T : class
{
try
{
DbContext.Set<T>().AddOrUpdate(row);
DbContext.SaveChanges();
return true;
}
catch (Exception ex)
{
return false;
}
}
public bool Delete<T>(T row) where T : class
{
return Update(row); //Pass an entity with IsActive = false and call update method
}
public bool AddRows<T>(T[] rows) where T : class
{
try
{
DbContext.Set<T>().AddOrUpdate(rows);
return true;
}
catch (Exception ex)
{
return false;
}
}
Et puis instancier et appeler la classe ici
public class MainLogicClassExample //Catty out logi operations on objects and update DataBase
{
public void NewEmailRecipient(EF.EmailRecipient recipient)
{
// logic operation here
EntityToDB(recipient);
}
public void NewReportRecipient(EF.ReportRecipient recipient)
{
// logic operation here
EntityToDB(recipient);
}
public void UpdateEmailRecipient(EF.EmailRecipient recipient)
{
// logic operation here
UpdateEntity(recipient);
}
public void UpdateReportRecipient(EF.ReportRecipient recipient)
{
// logic operation here
UpdateEntity(recipient);
}
// call generic methods to update DB
private void EntityToDB<T>(T entity) where T : class
{
var context = new ContextHelper<T>();
context.Insert(entity);
}
private void UpdateEntity<T>(T entity) where T : class
{
var context = new ContextHelper<T>();
context.Update(entity);
}
}
J'ai ajouté un DemoProject à GitHub ici: https://github.com/andyf1ynn/EntityFramwork-Generic-Type-DAL
Je vais vous décevoir - ce n'est * pas * le genre de problème avec des solutions rapides. –